【问题标题】:React context api, pass data from child to parentReact context api,将数据从孩子传递给父母
【发布时间】:2021-09-13 06:14:32
【问题描述】:

目前我在我的 react 应用程序中使用 reactjs context api,我想将数据从子组件传递到父组件,但我不确定如何实现。这是我的完整应用布局:

-  Component 1 (App.js) [contextOneProvider]
  -  Component 2  
    -  Component 3  ==> Need a state from child component 7
      -  Component 4
        -  Component 5 [contextOneConsumer, getting state from component 1]
          -  Component 6 
            -  Component 7 ==> Need to send a state to parent component 3
              -  Component 8 [contextOneConsumer, getting state from component 1]

正如你在上面看到的,我已经创建了一个 context(contextOne),contextOne 的提供者用于组件 1,c​​ontextOne 的消费者用于组件 5 和组件 8。现在父组件 3 需要一个数据/来自子组件 7 的状态,这就是问题所在,如何将子组件 7 中的一条数据/状态传递回父组件 3?

如果我在没有反应上下文 api 的情况下执行此操作,我需要将一个函数/方法从父组件 3 向下传递到子组件 7,然后在子组件 7 中调用它并备份数据/状态,我不会这样做想这样做,因为它是一个深支柱钻和组件4,组件5,组件6不需要那个功能/方法,它只存在于组件4,组件5和组件6是因为我需要它通过直到子组件 7 才能使用它。

我能想到的另一种方法是创建另一个新上下文(contextTwo)并在组件 3 上使用新上下文的提供者,在组件 7 上使用新上下文的提供者,但创建一个全新的上下文只是为了将一条数据/状态传回直到父组件 3,我也不认为这是一个好主意。

代码:

父组件 3

const componentThree = () => {
  return (
    <div>
      <span> // Receive someRandomId value from child component 7 and use in here </span>
      <ComponentFour/>
    </div>
  );
}

子组件 7

const componentSeven = () => {

  const handleOnClick = () => {
    // Pass someRandomId value back up to parent component 3
    const someRandomId = 4;
  };

  return (
    <div>
      <ComponentEight/>
      <button onClick={handleOnClick} ></button>
    </div>
  );
}

那么,如何在不进行道具钻探或创建全新上下文的情况下将一条数据/状态从子组件 7 传回父组件 3,只是为了将该一条数据/状态传回父组件?

抱歉,这是我第一次使用 react context api。

【问题讨论】:

    标签: javascript reactjs react-context


    【解决方案1】:

    按照以下步骤避免创建新上下文:

    在提供者组件中添加新状态:

    const [randonmId, setRandomId] = useState();
    

    randomIdsetRandomId 添加到传递给提供者的值

    value={{...previous things, randomId, setRandomId }}
    

    使用组件 3 中的上下文但仅获取 randomId

    另外,使用组件 7 中的上下文并在处理程序中使用 setRandomId

      const handleOnClick = () => {
        const someRandomId = 4;
        setRandomId(someRandomId);
      };
    

    在组件 3 中:

    {randomId && <span>{randomId}</span>}
    

    因为 randomId 在 comp 7 的处理程序被调用之前是未定义的

    【讨论】:

    • 嗨,抱歉,只是为了确保“将 randomIdsetRandomId 添加到传递给提供者的值中”您的意思是当前现有上下文的提供者(在组件 1 中)对吗?
    • @JustANewCoder 是的
    猜你喜欢
    • 2020-02-14
    • 1970-01-01
    • 2021-10-16
    • 1970-01-01
    • 2018-06-29
    • 2021-10-31
    • 1970-01-01
    • 2023-02-08
    • 2019-05-07
    相关资源
    最近更新 更多