Reactjs React上下文API可以';t绑定&x27;这';
当我在Reactjs React上下文API可以';t绑定&x27;这';,reactjs,this,bind,Reactjs,This,Bind,当我在组件内部的输入中键入任何内容时,我想执行组件内部的handleInput()函数 此(onChange={store.handleInput.bind(This)})看起来正常,但无法通过此 在控制台中,我只收到undefined消息 下面是一个示例代码 const MainContext=React.createContext() 类MainProvider扩展了React.Component{ 手动输入(e){ 控制台日志(e) } 渲染(){ 常数存储={ handleInput:(
组件内部的输入中键入任何内容时,我想执行
组件内部的handleInput()
函数
此(onChange={store.handleInput.bind(This)}
)看起来正常,但无法通过此
在控制台中,我只收到undefined
消息
下面是一个示例代码
const MainContext=React.createContext()
类MainProvider扩展了React.Component{
手动输入(e){
控制台日志(e)
}
渲染(){
常数存储={
handleInput:()=>this.handleInput()
}
返回(
{this.props.children}
)
}
}
类输入扩展了React.Component{
渲染(){
返回(
{(商店)=>(
)}
)
}
}
类应用程序扩展了React.Component{
渲染(){
返回(
)
}
}
如何在
onChange
事件中传递this
?我使用的是React 16.3.1。出现问题的原因是您在MainProvider组件中使用了arrow函数,该函数在调用函数时会覆盖传递的上下文
render () {
const store = {
handleInput: () => this.handleInput() // using arrow function here overrides the contect
}
}
换成
class MainProvider extends React.Component {
handleInput (e) {
console.log(e)
}
render () {
const store = {
handleInput: this.handleInput
}
return (
<MainContext.Provider value={store}>
{this.props.children}
</MainContext.Provider>
)
}
}
class MainProvider扩展了React.Component{
手动输入(e){
控制台日志(e)
}
渲染(){
常数存储={
handleInput:this.handleInput
}
返回(
{this.props.children}
)
}
}
但是,在这种情况下,您需要显式地从子组件绑定,否则它将从调用它的位置获取上下文。我意识到,如果我像您所说的那样使用,我无法访问
handleInput()函数中的此.state
。所以正确的答案应该是handleInput:this.handleInput.bind(this)
。通常情况下,您不需要onChange={store.handleInput.bind(this)}
,您在实现此函数的组件中通常会有一个绑定,因为您想知道为什么它不起作用,我提供了一个答案,还提到了,但是在这种情况下,您需要明确地从子组件绑定,否则它将从调用它的位置获取上下文。
现在我已经这样更改了我的代码:onChange={store.handleInput}
和handleInput:this.handleInput.bind(this)
。在handleInput()
函数中,我可以访问e
和this.state
。