Bad*_*ush 2 javascript reactjs
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>
)
}
}
Run Code Online (Sandbox Code Playgroud)
为什么不使用箭头功能?这将确保this正确引用.我假设你可以使用ES6.
function1 = () => {
console.log(this);
var param1 = 10;
const function2 = () => {
console.log(this);
var a = param1*2;
this.setState({ a });
}
function2(); // inkove the function
}
Run Code Online (Sandbox Code Playgroud)
或者,如果您只想使用ES5,那么这也可以
function1() {
console.log(this);
var param1 = 10;
function function2() {
console.log(this);
var a = param1*2;
this.setState({ a });
}
function2.bind(this)() // to invoke the function
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3196 次 |
| 最近记录: |