如何绑定'这'到react类之外的函数,后者是来自其他组件的回调

How to bind 'this' to functions outside react class which is a callback from other component?

本文关键字:函数 回调 其他 组件 绑定 何绑定 react      更新时间:2023-11-06

我有一个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"的值,以便它可以使用该组件的状态?

我真的不明白这个问题。我不知道这是不是你的意思,但如果你想保存"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>
}