美文网首页
React实战记录

React实战记录

作者: 坚果牛奶 | 来源:发表于2019-07-05 16:26 被阅读0次

点击按钮触发事件

尝试1:

<button onClick={this.showTable()}>Show Table</button>

返回错误信息:ReactJS: Maximum update depth exceeded error
原因: showTable()是去调用函数,因此render的时候会调用这个函数,然后页面更新,不停循环。

尝试2:
将函数调用改为函数引用

<button onClick={this.showTable}>Show Table</button>

返回错误信息:uncaught TypeError: Cannot read property 'setState' of undefined,错误位置为

ShowTable() {
      this.setState({
          show : !this.state.show
      });
 }

原因:不同于ES5可以直接这样调用函数修改内部属性,在ES6中需要进行事件和this绑定。

尝试3:

<button onClick={this.ShowTable.bind(this)}>Show Table</button>

成功。

再来看看其他方法:

//函数
ShowTable=()=> {
        this.setState({
            show : !this.state.show
        });
      }
//调用
<button onClick={this.handlerShowTable}>Show Table</button>

点击按钮时传参数

ShowTable(value) {
      this.setState({
          show : !this.state.show,
          name: value
      });
 }
<button onClick={this.ShowTable.bind(this, value)}>Show Table</button>

相关文章

网友评论

      本文标题:React实战记录

      本文链接:https://www.haomeiwen.com/subject/mzeehctx.html