簡體   English   中英

我如何在React中使用children道具刪除組件

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

我正在嘗試實現這種情況:

  1. 我的酒吧道具有Foo組件

  2. 如果bar prop為true- > 安裝 Foo組件內部的Bar組件

  3. 如果bar prop為false- > 卸載Bar組件
  4. 我不希望Example組件知道此顯示/隱藏,我只希望Foo知道何時顯示或隱藏它
  5. 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阻止我自己修改孩子。

我是否需要外部服務來在這兩個組件之間進行通信?

我應該使用上下文嗎?

尋找有關如何解決此問題的建議。

一種可能的解決方案是使用某種消息總線或pubSub。 在這種方法中,Bar組件將必須訂閱總線,並顯示/隱藏自身。 Foo組件將在componentWillReceiveProps中發布適當的消息。 更多: 這里

一種簡單的解決方案是在Foo component Bar component內部使用Bar component ,並根據ternary condition渲染。

還返回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