2017-09-26 71 views
0

我有4个组件。我只想一次渲染一个。我有我的导航按钮,当我点击一个它应该渲染该组件,然后隐藏其他3(即将它们设置为空)在点击按钮时切换组件的响应

这很容易与2个组件。我只是有一个切换功能,像这样:

toggle() { 
    this.setState(prevState => ({ 
    showTable: !prevState.showTable 
    })); 
} 

我试图去适应这个现在在那里我有这样的:

showComponent(component) { 
    this.setState(prevState => ({ 
    [component]: !prevState.component 
    })); 
} 

这目前显示当我点击相应的按钮组件。但是,一旦再次单击相同的按钮,它将不会隐藏组件。

我有我的所有按钮调用此方法像这样:

<button onClick={() => this.showComponent('AddPlayer')}>Add</button> 
<button onClick={() => this.showComponent('ShowPlayers')}>Players</button> 
<button onClick={() => this.showComponent()}>Table</button> 
<button onClick={() => this.showComponent()}>Matches</button> 

什么想法?

编辑:

{this.state.AddPlayer ? 
       <div className="add-container"> 
       <AddPlayer /> 
       </div> 
       : 
       null 
      } 
      {this.state.ShowPlayers ? 
       <div className="players-container"> 
       <Players /> 
       </div> 
       : 
       null 
      } 
+0

可以展开的问题,以显示正在显示/隐藏的组件? – Chris

+0

你可以发布你的渲染方法吗?这样我可以回答好@The海象 –

+0

是的我的坏,它的存在,现在 –

回答

0

您可以通过多种方式做到这一点,

的一种方法是,创建与所有国家的价值观和组件的常量像

const components = { 
    "AddPlayer": <AddPlayer />, 
    "ShowPlayers": <Players />, 
    "Something1": <Something1 />, 
    "Something2": <Something2 /> 
} 

设定值状态像

showComponent(componentName) { 
    this.setState({displayedTable: componentName}); 
} 

和内部渲染简单

render(){ 
    return(
     <div> 
      {components[this.state.displayedTable]} 
     </div> 
    ) 
} 

使用开关箱

renderComponent(){ 
    switch(this.state.displayedTable) { 
    case "AddPlayer": 
     return <AddPlayer /> 
    case "ShowPlayers": 
     return <Players /> 
    } 
} 

render() { 
    return (
     <div> 
      { this.renderComponent() } 
     </div> 
    ) 
} 
+0

遗憾的一件事,如果IM传递的东西变成像这样的组件: '<表 玩家= {}球员 />' 如何我能解决这个问题吗?它说球员是不确定的,这是因为球员是依赖于状态(但我已经把上述所有内部状态?) –

+0

不要担心,修复。将其移出状态 –