传统HTML中<div onclick="handleclick()"></div>handleclick函数自动绑定了this,而react中<div onClick={handleclick}"></div>需要手动绑定,下面是回调函数绑定this的三种方法
1.bind(this)
constructor(props){
super(props);
this.state={};
this.functionname=this.functionname.bind(this);
}
属性初始化器
functionname(){
console.log("this is",this);
//function here...
}
箭头函数
render(){
return(
<div onClick={(e)=>(this.function(e))}></div>
)
}
2.HTML中阻止事件的默认行为可以用return false
<a href="#" onclick="console.log('The link was clicked.'); return false">
Click me
</a>
而React中只能显示调用e.preventDefault();
function ActionLink() {
function handleClick(e) {
e.preventDefault();
console.log('The link was clicked.');
}
return (
<a href="#" onClick={handleClick}>
Click me
</a>
);
}
组件可以用函数和类定义,但是只有类定义的组件有局部状态和生命周期钩子. this.props 和 this.state 可能是异步更新的,不应该依靠它们的值来计算下一个状态。例如,此代码可能无法更新计数器:
// Wrong
this.setState({
counter: this.state.counter + this.props.increment,
});