Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/258.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs React上下文API可以';t绑定&x27;这';_Reactjs_This_Bind - Fatal编程技术网

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