04.React 事件绑定

 ̄綄美尐妖づ 提交于 2020-01-15 02:38:43

04.React 事件绑定

1.事件与原生事件类型 react中式on+首字母大写的事件名 例如onClick
2.普通函数和箭头函数

<button
          onClick={function() {
            alert("普通函数");
          }}
        >
          按钮1
        </button>
<button
          onClick={() => {
            alert("箭头函数");
          }}
        >
          按钮2
        </button>

3.直接绑定函数
3.1不使用this

show4() {
    alert("直接绑定函数不能使用this");
  }
  <button onClick={this.show4}>按钮4</button>

3.2使用箭头函数 使用this

show5 = () => {
    alert("用箭头函数让this指向类 " + this.state.date);
  };
<button onClick={this.show5}>按钮5</button>

3.3用bind绑定this

constructor(props) {
    super(props);
    this.state = {
      date: new Date().toLocaleDateString()
    };
  }
show8() {
    alert("写法跟4相同但是要绑定bind   " + this.state.date);
  }
  <button onClick={this.show8.bind(this)}>按钮8</button>

3.4 用bind绑定this 但是在state里面

constructor(props) {
    super(props);
    this.state = {
      date: new Date().toLocaleDateString()
    };
    this.show9 = this.show9.bind(this);
  }
show9() {
    alert("这次是在state里面绑定bind   " + this.state.date);
  }
<button onClick={this.show9}>按钮9</button>

4.传参 传数据源

show7 = (con, e) => {
    e.target.innerHTML = con;
  };
<button
          onClick={e => {
            this.show7("既可以传参,也可以带事件源", e);
          }}
        >
          按钮7
        </button>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!