之前的文章我们介绍了 React 绑定属性 ( 绑定 class 绑定 style), 引入图片 循环数组渲染数据. 接下来我们将介绍 React 事件, 方法, React 定义方法的几种方式 获取数据 改变数据 执行方法传值.
- import React, {Component} from 'react';
- class Home extends Component {
- constructor(props) {
- super(props);
- this.state = {
- name: "zhangsan",
- };
- this.getData2 = this.getData2.bind(this);
- }
- getData1() {
- console.log(this.state.name)
- }
- getData2() {
- console.log(this.state.name)
- }
- getData3 = () => {
- console.log(this.state.name)
- }
- setData = (name) => {
- this.setState({
- name: name
- })
- }
- render() {
- return (
- <div>
- <p>Hello {this.state.name}</p>
- <button onClick={this.getData1.bind(this)}> 获取数据 1</button>
- <button onClick={this.getData2}> 获取数据 2</button>
- <button onClick={this.getData3}> 获取数据 3</button>
- <button onClick={this.setData.bind(this, "lisi")}> 改变数据 </button>
- </div>
- );
- }
- }
- 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({ 要改变的数据变量名: 更改的数据 }) 的方法.
最后运行结果如下:
来源: https://www.cnblogs.com/weijiutao/p/10648369.html