如何将“this”绑定到react类之外的函数,这是来自其他组件的回调?

IT技术 javascript reactjs this
2021-05-10 05:11:11

我有一个 React 组件,例如:

function callback(params){..
// I need to use this.setstate but this callback function is called 
// from other component. How do I bind value of this here 
// 'this' of RespProperties
...
}

class RespProperties extends Component { ..
 ...
}

这个回调函数是从其他组件调用的。如何在此处绑定“this”的值,以便它可以使用此组件的状态?

2个回答

我真的不明白这个问题。我不知道这是否是您的意思,但是如果您想保存“this”临时变量,那么只需创建一个全局数组或单个变量来存储“this”。

var thisTemp;

function callback(params){..
// use variable here
thisTemp.blah();
...
}

class RespProperties extends Component { ..
//Assign this to thisTemp
thisTemp = this;
...
}

您可以分离此共享功能,将其留在组件之外,然后使用bind

function callback(params){
    this.setState({ works: true });
}

class RespProperties extends Component {
    state = { works: false }
    ...
    render = () => <button onClick={callback.bind(this)}>Click</button>
                                 // ^ here we use .bind(this) to... well...
                                 //   bind `this` so we can use it in the function xD
}

class SomeOtherComponent extends Component {
    state = { works: false }
    ...
    render = () => <button onClick={callback.bind(this)}>I'm from some other component</button>
}