簡體   English   中英

如何訪問react Context.Provider值內的另一個函數?

[英]How can I access another function inside the react Context.Provider value?

目前,我學習了如何使用react context API。 我有一個react Provider類,在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()必須是一個獨立的可訪問函數。

誰能幫我? 謝謝!

您可以嘗試做的是:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM