[英]How to pass React Component prop to child function using {children}?
[英]How can I remove a component using the children prop in React
我正在嘗試實現這種情況:
我的酒吧道具有Foo組件
如果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';
我試圖操縱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.