问题
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