【发布时间】:2018-01-04 05:06:26
【问题描述】:
我正在尝试实现这种情况:
我有 Foo 组件 和 bar prop
如果 bar prop 为 true --> mount Bar 组件 位于 Foo 组件内
- 如果 bar 属性为 false --> 卸载 Bar 组件
- 我不想让示例组件知道这个显示/隐藏,我只想让 Foo 知道何时显示或隐藏它
- Bar 不一定是 Foo 的直接子级,它也可以嵌套在 Foo 的子级中更深
const Example = () => { return ( <Foo bar={true/false}> <div>some div</div> <Bar></Bar> </Foo> ) }; class Foo extends React.Component { componentWillReceiveProps({bar}) { if (bar) { /* I want to show bar!! */ } else { /* I want to remove only bar!! */ /* maybe doing something like: this.props.children.searchForBar().removeNode() */ } } render () { return ( <div>{this.props.children}</div> ) } }; const Bar = () => 'I am some bar';
我试图操纵 this.props.children 但 React 阻止我自己修改孩子。
这两个组件之间的通信是否需要外部服务?
我应该使用上下文吗?
寻求有关如何解决此问题的建议。
【问题讨论】:
-
是的,如果你想切换
即使 的孩子,你也需要外部的东西来处理状态(比如 redux)不是
标签: javascript reactjs jsx