【问题标题】:Redux react inter-component communicationRedux react 组件间通信
【发布时间】:2017-09-12 13:28:22
【问题描述】:

我有以下简化的组件结构

ChildC10 基本上是一个列表,每个项目都有一堆复选框。用户可以从此列表中选择一个或多个。

ChildC1 包含一个按钮,单击时应选择在 ChildC10 中选中的项目。我如何使用 React、Redux 来做到这一点。

【问题讨论】:

    标签: reactjs redux


    【解决方案1】:

    父级应该有一个本地状态,包含从列表中选择的元素。 ChildC10 将有一个道具,它是在列表项目的 onPress 上触发的函数。此函数将使用 setState 从父项中添加/删除项。

    ChildC1 会有一个道具 onPress 可以对状态做一些事情。

    父母应该是这样的

    export default class Parent extends Component {
    
      state = {
        selectedItems: [],
      }
    
      render() {
        return (
          <div>
            <ChildC10
                selectedItems={this.state.selectedItems}
                onItemPressed={(item) => {
                  const currentList = this.state.selectedItems;
                  //Find if item already in it
                  //Modify (add or remove) the element from currentList
                  this.setState({selectedItems: currentList})
              }}
            />
            <ChildC1 onButtonPress={() => /*do the thing you want to do with the selectedItems. You have access to it in the state*/}/>
          </div>
        );
      }
    }
    

    您可以使用您想要存储所选项目的结构。如果你想调用一个动作来进行 API 调用,我会在 Parent 中调用这个动作。我不会将 ChildC1 绑定到 Redux,因为它是一个愚蠢的组件,应该只做视觉上的事情。容器(在您的情况下是父级)是应该具有逻辑的容器。

    如果不是这样,忘记最后一段,只检查代码:P

    希望对你有帮助!

    【讨论】:

      猜你喜欢
      • 2017-11-08
      • 2018-05-31
      • 2017-04-07
      • 2015-09-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-28
      • 1970-01-01
      相关资源
      最近更新 更多