首页 > 其他 > 详细

react绑定this另一种方法

时间:2019-05-19 16:46:14      阅读:106      评论:0      收藏:0      [点我收藏+]

代码如下:

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绑定this另一种方法

原文:https://www.cnblogs.com/zhx119/p/10889711.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!