简体   繁体   English

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

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

I have a React Component such as : 我有一个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 callback function is called from some other component. 从其他组件调用此回调函数。 How do I bind value of 'this' here so that it can use states of this component? 如何在这里绑定“ this”的值,以便它可以使用此组件的状态?

I don't really understand the question. 我不太明白这个问题。 I don't know if this is what you mean, but if you want to save the 'this' temporary variable, then just create a global array or single variable to store the 'this'. 我不知道这是什么意思,但是如果要保存'this'临时变量,则只需创建一个全局数组或单个变量来存储'this'。

var thisTemp;

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

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

You could separate this shared function, leaving it outside the components, then use bind : 您可以分离此共享功能,将其保留在组件之外,然后使用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>
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM