简体   繁体   English

我如何在React中使用children道具删除组件

[英]How can I remove a component using the children prop in React

I am trying to achieve this scenario: 我正在尝试实现这种情况:

  1. I have Foo component with bar prop 我的酒吧道具有Foo组件

  2. If bar prop is true --> mount Bar component that is inside the Foo component 如果bar prop为true- > 安装 Foo组件内部的Bar组件

  3. if bar prop is false --> unmount Bar component 如果bar prop为false- > 卸载Bar组件
  4. I don't want Example component to be aware of this show/hide, I want only Foo to know when to show or hide it 我不希望Example组件知道此显示/隐藏,我只希望Foo知道何时显示或隐藏它
  5. Bar is not necessary a direct child of Foo, it can also be nested deeper in the children of 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'; 

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM