this
处理嵌套函数时如何绑定到 React 组件?
这是一个骨架示例。function2
嵌套的原因是这样您就可以访问中定义的变量function1
class View extends Component{
constructor(props){
this.function1 = this.function1.bind(this);
this.state = {
a = null;
}
}
componentDidMount(){
function1();
}
function1(){
console.log(this); //will show the component correctly
var param1 = 10;
//call a second function that's defined inside the first function
function2();
function function2(){
console.log(this); //undefined
var a = param1*2;
this.setState({ a : a}); //won't work because this is undefined
}
}
render(){
return(
<div>
<p> Hello </p>
</div>
)
}
}