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

社会主义新天地 提交于 2020-01-30 12:26:46

问题


I have a React Component such as :

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?


回答1:


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'.

var thisTemp;

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

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



回答2:


You could separate this shared function, leaving it outside the components, then use 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>
}


来源:https://stackoverflow.com/questions/36372509/how-to-bind-this-to-functions-outside-react-class-which-is-a-callback-from-oth

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!