添加方法以响应上下文

时间:2019-05-21 10:05:41

标签: javascript reactjs

所以我有一个看起来像这样的应用程序(试图尽可能简化):

// file with context
const SomeContext = React.createContext({});
// file with app root
class App extends Component {
  constructor() {
    super();
    this.state = {
      someValue: 123
    };
  }

  doSomething() {
    // this does not work,
    // as "this" is context value
    this.setState({
      someValue: someValue + 1
    });
  }

  render() {
    // create context values
    const value = {
      someValue: this.state.someValue
      doSomething: this.doSomething
    };
    return <SomeContext.Provider value={value}><ChildComponent/></SomeContext>;
  } 
}
// file with child component
class ChildComponent extends Component {
  render() {
    return <button onClick={this.context.doSomething} />
  }
}
ChildComponent.contextType = SomeContext;

我希望上下文具有doSomething方法来更新应用程序的状态(特别是将someValue增加1)。

如何从子组件正确执行doSomething方法?

我必须做doSomething: this.doSomething.bind(this)吗?还是有更好的方法?

编辑问题不是关于如何获得“ this”的问题,而是关于在这种情况下推荐的方法是什么。也许我根本不应该在上下文中添加方法?

0 个答案:

没有答案