react绑定this另一种方法

代码如下:

import React from 'react';
class Component extends React.Component{
constructor(props){
super(props);
this.state={
name : 'Rosen',
age : 18
}
this.handleClick = this.handleClick.bind(this);
}
handleClick(){
this.setState({
age : this.state.age + 1
});
}
onValueChange(e){
this.setState({
age : e.target.value
});
}
render(){
return (
<div>
<h1>I am {this.state.name}</h1>
<p>I am {this.state.age} years old!</p>
<button onClick={this.handleClick}>加一岁</button>
<input type="text" onChange={(e) => {this.onValueChange(e)}}/>
</div>
);
}
}

function App() {
return (
<div className="App">
<Component/>
</div>
);
}

export default App;
这里handleClick方法绑定到button上this.handleClick要想有效必须在constructor中设置this.handleClick = this.handleClick.bind(this),绑定this才可以正常使用否则会报错,也可以如下的
代码实现绑定:
import React from 'react';
class Component extends React.Component{
constructor(props){
super(props);
this.state={
name : 'Rosen',
age : 18
}
// this.handleClick = this.handleClick.bind(this)
}
handleClick(){
this.setState({
age : this.state.age + 1
});
}
onValueChange(e){
this.setState({
age : e.target.value
});
}
render(){
return (
<div>
<h1>I am {this.state.name}</h1>
<p>I am {this.state.age} years old!</p>
<button onClick={ () =>{this.handleClick()}}>加一岁</button>
<input type="text" onChange={(e) => {this.onValueChange(e)}}/>
</div>
);
}
}

function App() {
return (
<div className="App">
<Component/>
</div>
);
}

export default App;
通过箭头函数执行该方法就不用绑定this了
 react 子组件通过props接收父组件传递的数据,子组件改变父组件的数据,也是通过props接收的方法绑定到props来出发父组件的数据改变。
原文地址:https://www.cnblogs.com/zhx119/p/10889711.html