React-5-事件

先看例子

import React from 'react';
import ReactDOM from 'react-dom';
class Toggle extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            isToggleOn: true
        };
        //this.handleClick = this.handleClick.bind(this);

    }
    handleClick() {
        //  console.log(this)
        this.setState(
            {
                isToggleOn: false
            })

    }
    render() {
        //console.log(this)
        return (

            <button onClick={this.handleClick}>
        {this.state.isToggleOn ? 'ON' : 'OFF'}
      </button>
        );
    }
}

ReactDOM.render(
    <Toggle />,
    document.getElementById('root')
);

但是点击按钮的时候,报错了。

按上图的打印this,只有在构造函数,将handleClick通过bind绑定this,handleClick()函数里的this才能指向Toggle。

当然render函数里this一直指向Toggle。

总之handleClick中的this没有指向Toggle,所以this.setState方法也就不存在了。

所以要使用this.handleClick = this.handleClick.bind(this);

那么,为什么onClick={this.handleClick},this指向变了呢。

看看官方给出的解释

接下来完善这个代码

import React from 'react';
import ReactDOM from 'react-dom';

class Toggle extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            isToggleOn: true
        };
        this.handleClick = this.handleClick.bind(this);
     
    }
    handleClick() {
             this.setState(
            {
                isToggleOn: this.state.isToggleOn?false:true
            })

    }
    render() {
        return (

            <button onClick={this.handleClick}>
        {this.state.isToggleOn ? 'ON' : 'OFF'}
      </button>
        );
    }
}

ReactDOM.render(
    <Toggle />,
    document.getElementById('root')
);

 接下里看如何向事件处理函数传递参数

<button onClick={(e) => this.deleteRow(id, e)}>Delete Row</button>
<button onClick={this.deleteRow.bind(this, id)}>Delete Row</button>

测试如下

     <button  onClick={this.handleClick.bind(this,123)}>

  handleClick(i) {
        console.log(i)//结果123
         }

另一种方式

<button  onClick={(e)=>this.handleClick(123,e)}>

handleClick(i) {
        console.log(i)
    }
 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章