gpt4 book ai didi

reactjs - React Context API无法绑定(bind) 'this'

转载 作者:行者123 更新时间:2023-12-03 14:18:51 24 4
gpt4 key购买 nike

当我在 <Input> 内的输入中输入任何内容时组件,我想执行 handleInput() <MainProvider> 内部的函数组件。

这个( onChange={store.handleInput.bind(this)} )看起来可以工作,但它无法通过 this .

在控制台中我刚刚得到 undefined消息。

这是一个示例代码。

const MainContext = React.createContext()

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 Input extends React.Component {
render () {
return (
<MainContext.Consumer>
{(store) => (
<input {...this.props} onChange={store.handleInput.bind(this)} />
)}
</MainContext.Consumer>
)
}
}

class App extends React.Component {
render () {
return (
<MainProvider>
<Input name='one' />
<Input name='two' />
</MainProvider>
)
}
}

如何通过thisonChange事件?我正在使用 React 16.3.1。

最佳答案

问题的出现是因为您在 MainProvider 组件中使用了箭头函数,该函数覆盖了调用函数时传递的上下文

  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>
)
}
}

但是在这种情况下,您将明确需要从子组件进行绑定(bind),否则它将从调用它的位置获取上下文。

关于reactjs - React Context API无法绑定(bind) 'this',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49792610/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com