之前的文章我们介绍了 React 绑定属性( 绑定class 绑定style)、引入图片 循环数组渲染数据。接下来我们将介绍 React 事件,方法, React定义方法的几种方式 获取数据 改变数据 执行方法传值。
1 import React, {Component} from \'react\'; 2 3 class Home extends Component { 4 constructor(props) { 5 super(props); 6 this.state = { 7 name: \"zhangsan\", 8 }; 9 10 this.getData2 = this.getData2.bind(this); 11 } 12 13 getData1() { 14 console.log(this.state.name) 15 } 16 17 getData2() { 18 console.log(this.state.name) 19 } 20 21 getData3 = () => { 22 console.log(this.state.name) 23 } 24 25 setData = (name) => { 26 this.setState({ 27 name: name 28 }) 29 } 30 31 render() { 32 return ( 33 <div> 34 <p>Hello {this.state.name}</p> 35 36 <button onClick={this.getData1.bind(this)}>获取数据1</button> 37 <button onClick={this.getData2}>获取数据2</button> 38 <button onClick={this.getData3}>获取数据3</button> 39 <button onClick={this.setData.bind(this, \"lisi\")}>改变数据</button> 40 </div> 41 ); 42 } 43 } 44 45 export default Home;
React 上绑定方法共有三种方法:
首先我们在 onClick 点击时间中直接绑定 this.getData 方法的时候如果写成 this.getData( ) 的话会直接调用该方法,所以不能写 ( ),
在不写 () 的情况下,后点击运行 getDate 方法获取 this.state 里面的数据会报错,这是因为this指向发生了变化。绑定 this 指向有一下方法:
1、this.getData1.bind(this),在该方法后面直接写 .bind(this),在运行 getData1 方法的时候 this 指向不会发生变化。
2、this.getData2 = this.getData2.bind(this),在 constructor 构造函数中直接将 getData2 方法绑定上 this.
3、this.getData ,然后在调用该方法的时候 getData3 = () => { },运用箭头函数的方法直接将 this 指向上下文。
在实际开发应用中我们建议使用第三种方法。
在方法中传值需要使用 this.setData.bind(this, 值) 的方法,第一个参数为 this,第二个参数为要传的值。
在方法中要改变 this.state 中的数据时需要使用 this.setState({ 要改变的数据变量名:更改的数据 }) 的方法。
最后运行结果如下: