[英]How can I remove a component using the children prop in React
I am trying to achieve this scenario: 我正在尝试实现这种情况:
I have Foo component with bar prop 我的酒吧道具有Foo组件
If bar prop is true --> mount Bar component that is inside the Foo component 如果bar prop为true- > 安装 Foo组件内部的Bar组件
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';
I've tried to manipulate this.props.children but React blocked me from modifying children myself. 我试图操纵this.props.children,但是React阻止我自己修改孩子。
Do I need maybe an outer service for communication between these 2 components ? 我是否需要外部服务来在这两个组件之间进行通信?
Should I use context maybe ? 我应该使用上下文吗?
Looking for an advice on how to approach this issue. 寻找有关如何解决此问题的建议。
One of possible solutions is to use some kind of message bus or pubSub. 一种可能的解决方案是使用某种消息总线或pubSub。 In that kind of approach, Bar component would have to subscribe to the bus, and show/hide itself.
在这种方法中,Bar组件将必须订阅总线,并显示/隐藏自身。 Foo component would publish appriopriate messages in componentWillReceiveProps.
Foo组件将在componentWillReceiveProps中发布适当的消息。 More: here
更多: 这里
One simple solution is to use Bar component
inside of the Foo component
and render that based on a ternary condition
. 一种简单的解决方案是在
Foo component
Bar component
内部使用Bar component
,并根据ternary condition
渲染。
Also return a JSX element(Valid react element from Bar component) rather than a string. 还返回JSX元素(来自Bar组件的有效react元素)而不是字符串。
const Example = () => { return ( <Foo bar={true}> <div>some div</div> </Foo> ) }; class Foo extends React.Component { render () { return ( <div> <div>{this.props.children}</div> {this.props.bar? <Bar />: null} </div> ) } }; const Bar = () => <div>I am some bar</div>; ReactDOM.render(<Example/>, document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.js"></script> <div id="app"></div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.