【问题标题】:How to communicate from Child Component to Parent Component with React Router如何使用 React Router 从子组件通信到父组件
【发布时间】:2016-02-07 12:09:26
【问题描述】:

我有一个主要组件App,根据路线包含一些孩子(我使用react-router)等:

class App extends Component {

    otherClick = () => { /* run every children's `handleButton2` function */ }
    <div className="App">
         <Button handleMenuClick={this.toggleSideBar}>Button 1</Button>
         <Button handleOtherClick={this.otherClick}>Button 2</Button>
         <SideBar ref="sideBar" title="Toto"/>
          {this.props.children}
    </div>
    }

因此,根据路由,App 将包含一些其他容器,例如:

class ContainerABC extends React.Component {
    constructor(props) {
        super(props);
    }
    handleButton2 = () => {
        let sc = this.refs.subCont;
        sc.setState({visible : !sc.visible});
        // Change the color of Button 2 ???
    };
    render() {
        return (
            <div>
            <SubContainer ref="subCont"/>
            </div>
        );
    }
};

Button 2 的作用取决于当前的 Container。在上面的例子中,当我有一个ContainerABC 作为孩子时,我希望Button 2 切换SubContainerContainerABC

如何告诉 Button 2 根据组件的子级执行适当的操作? 和/或当Button 2 触发SubCont 上的操作时,如何从SubCont 修改Button 2(或任何触发器)?

也许使用 Redux ?我看不出它有什么帮助

【问题讨论】:

    标签: reactjs react-router redux


    【解决方案1】:

    Redux 可能 有帮助,只是因为它可以触发一个动作,作为回报,修改全局状态树(例如,redux 通过 reducer 存储)。如果这是您需要实现的唯一目的,那么我建议不要增加复杂性(尽管我喜欢 Redux)。

    我假设您希望来自{this.props.children} 的随机孩子在单击按钮 2 后触发随机操作?

    让我们观察一下这种常用的 React 模式: 属性向下流动。操作(阅读:回调)向上。

    也就是说,您可能希望遍历您的 {this.props.children} 并检查是否存在符合您的 API 要求的特殊回调道具。

    React.Children.forEach(this.props.children, (child) => {
        if (typeof child.props.toggleButton2State !== "function")   {
            throw('Woah, cowboy, you need that toggleButton2State function);
        }
    }
    

    然后您的按钮可以以相同的方式在子项之间循环并执行该功能(如果存在)。

    handleButton2Click() {
        React.Children.forEach(this.props.children, (child) => {
            if (typeof child.props.toggleButton2State === "function")   {
                child.props.toggleButton2State.call(child, !oldState, this);
            }
        }
    }
    

    因此,您刚刚在子范围内调用了子级回调函数,并且布尔状态被切换,并且您还传递了对父组件的引用 (this)。

    我强烈建议您永远不要从孩子那里操纵父容器。你永远不知道你的层次结构会如何改变。

    显然,这是一个非常粗略的示例,但它应该可以让您继续前进。让我知道事情的后续。

    【讨论】:

    • 如何将toggleButton2State 从孩子暴露给父母?因为父级无权访问子级方法并且它实际上不是prop
    • 你没有。属性向下(父级到子级),动作向上(通过 props 提供的回调形式)。
    • 所以你的解决方案不起作用。我将使用 redux 会更容易。因为,我不知道父级中包含的子级。所以父母不能传递道具。该函数是子组件的一部分
    • 现在孩子们可以触发一个修改Button2状态的动作
    • 我给了你赏金,因为你的答案很有趣
    【解决方案2】:

    如果按钮的行为取决于正在呈现的容器,那么在我看来,容器应该呈现按钮。您可以连接一些道具(甚至可以使用cloneElement 将它们放在孩子身上),这样您就可以向下传递回调,这会改变按钮的行为,但这听起来像是一场噩梦。

    您可以将这些按钮放在一个单独的组件中(使用一个属性来确定它们的作用)并将其呈现在容器中。这对我来说听起来要简单得多。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-01-02
      • 2018-04-08
      • 2019-12-04
      • 2017-12-20
      • 2017-05-18
      • 2018-09-08
      • 2017-10-02
      • 2018-05-25
      相关资源
      最近更新 更多