如何访问反应Context.Provider值中的另一个函数?

问题描述 投票:0回答:1

目前,我学习了如何使用react context API。我有一个react类,在value={}中有一些状态数据和函数。如何在此值内的另一个函数中访问此值内的函数?

因此,function1()由子组件调用。状态更改完成后,我想调用function2()并访问新状态。

是否有可能做出这样的反应?:

class Provider extends Component {
  state = {
    foo: 'bar'
  }

  render() {
    return() {
      <Context.Provider value={{
        state: this.state,

        function1: () => {
          this.setState({ foo: 'changed' }, () => {
            // HERE I WANT TO CALL THE NEXT FUNCTION IN THIS VALUE
            this.function2()
          });
        },

        function2: () => {
          // called by function1 after state change
          console.log(this.state)
        }
      }}>
        { this.props.children }
      </Context.Provider>
    }
  }
}

如果我试图运行它,并从孩子那里解雇function1(),它就会给我

TypeError: _this2.function2() is not a function

我不明白,为什么它试图访问_this2变量,因为我定义它来访问this.function2()

难道不能做我想要的反应吗?你可能会说,为什么function2()是一个额外的函数,为什么我不在function1()的末尾添加代码。这是因为function2()必须是一个独立的可访问功能。

谁能帮我?谢谢!

javascript reactjs
1个回答
1
投票

你可以尝试做的是: -

class Provider extends Component {
    state = {
    foo: 'bar'
  }

  an_independent_function() {
    console.log(this.state);
  }

  render() {
    return() {
      <Context.Provider value={{
        state: this.state,

        function1: () => {
          this.setState({ foo: 'changed' }, () => {
            // HERE I WANT TO CALL THE NEXT FUNCTION IN THIS VALUE
            this.an_independent_function();
          });
        },

        function2: this.an_independent_function.bind(this)
      }}>
        { this.props.children }
      </Context.Provider>
    }
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.