2017-07-28 115 views
0

我想实现这个场景我删除组件:如何使用孩子托在阵营

  1. 富组件吧托

  2. 如果酒吧道具true - >安装Bar组件即Foo组件内

  3. 如果酒吧道具 - >卸载栏组件
  4. 我不想例组件要知道这显示/隐藏的,我只想要富,知道什么时候可以显示或隐藏它
  5. 酒吧是没有必要美孚的直接孩子,也可以在美孚的孩子
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'; 

我已经特里嵌套更深d来操纵this.props.children,但React阻止我自己修改孩子。

我需要一个外部服务来进行这两个组件之间的通信吗?

我应该用上下文吗?

寻找关于如何解决此问题的建议。

+0

是的,你需要从外面的东西来处理状态(如终极版),如果你想切换即使是不是我想窝

回答

1

可能的解决方案之一是使用某种消息总线或pubSub。在这种方法中,酒吧组件将不得不订阅公共汽车,并显示/隐藏自己。 Foo组件将在componentWillReceiveProps中发布appriopriate消息。更多:here

1

一个简单的解决方案是使用Bar componentFoo component和渲染根据ternary condition

还返回一个JSX元素(来自Bar组件的有效反应元素)而不是字符串。

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>

+0

孩子酒吧外的酒吧。我基本上试图了解组件如何具有它可以意识到的“子组件”。所以Foo是主要组件,但它可以控制像Bar这样的子组件并隐藏它,即使Bar不在Foo内 – Alon