![](/img/trans.png)
[英]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.