react基础--事件的写法

谈react事件写法前,先梳理一下关于react的学习的思路。

和其他框架一样,react的学习依次要解决几个问题:

1.框架如何运行;

2.页面样式、事件、数据的写法;

3.组件----组建中数据、事件的写法,组件间的通讯(数据传递);

4.路由----页面的跳转

5.数据请求----ajax

6.数据的管理----全局的状态切换、数据的缓存

掌握事件写法的重要性不言而喻,以下梳理几种事件的写法,以及应用场景。

react中事件的写法,个人认为主要分为两大类,当然根据框架分离的思想,我们肯定主要使用第二种。

1.声明和调用都在render里:写法主要分为普通函数;箭头函数;带事件源。

2.函数的定义和调用分离:其中涉及到this指向问题,需要注意。=》解决:箭头函数;箭头函数带参数;箭头函数带事件源和参数;调用时bind改变指向;声明时bind改变指向。

废话不多说,直接上代码。每个按钮分别代表不同的方法执行结果
 

import React, { Component } from 'react'
 
export default class Footer extends Component {
    constructor(props) {
        super(props);
        this.state = {
            num: 111
        }
        this.show8=this.show8.bind(this);
    }
    show4(){
        alert("4号被点击");
        // alert(this.state.num);这个会报错,因为this指向window,找不到state,undefined
    }
    show5=()=>{
        alert(this.state.num)
    }
    show6=(cont)=>{
        alert(cont);
    }
    show7=(cont,e)=>{
        e.target.innerHTML=cont;
    }
    show8(){
        alert(this.state.num);
    }
    show9(){
        alert(this.state.num);
    }
    
    render() {
        return (
            <div className="footer">
                我是底部{this.state.num}
                //声明和调用在一起,这样代码不好看,也不适合复杂操作
                <button onClick={function () { alert("666")}}>按钮1</button>
                <button onClick={() => { alert("8888") }}>按钮2</button>
                <button onClick={
                    (e) => {
                        e.target.innerHTML = "7777"
                    }}>按钮3</button>
                //声明调用分离,this指向不对,要手动调整
                <button onClick={
                    this.show4
                }>按钮4</button>
                <button onClick={this.show5}>按钮5</button>
                <button onClick={
                    ()=>{
                        this.show6("我是传的参数9999")
                    }
                    }>按钮6</button>
                <button onClick={
                    (e)=>{
                        this.show7("点击变内容",e)
                    }
                }>按钮7</button>
                <button onClick={this.show8}>按钮8</button>
                <button onClick={this.show9.bind(this)}>按钮9</button>
            </div>
        )
    }
 
}
发布了1 篇原创文章 · 获赞 0 · 访问量 8

猜你喜欢

转载自blog.csdn.net/qq_27292445/article/details/103979494