切换组件以响应按钮单击

The*_*rus 1 javascript components toggle reactjs

我有4个组件。我只想一次渲染一个。我的导航中有按钮,当我单击一个按钮时,它应该呈现该组件,然后隐藏其他 3 个(即将它们设置为 null)

这很容易使用 2 个组件。我只有一个像这样的切换功能:

toggle() {
  this.setState(prevState => ({
    showTable: !prevState.showTable
  }));
}
Run Code Online (Sandbox Code Playgroud)

我已经尝试在我有这个的地方调整这个:

showComponent(component) {
  this.setState(prevState => ({
    [component]: !prevState.component
  }));
}
Run Code Online (Sandbox Code Playgroud)

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

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

<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>
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?

编辑:

{this.state.AddPlayer ?
              <div className="add-container">
                <AddPlayer />
              </div>
              :
              null
            }
            {this.state.ShowPlayers ?
              <div className="players-container">
                <Players />
              </div>
              :
              null
            }
Run Code Online (Sandbox Code Playgroud)

Nar*_*ker 9

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

一种方法是,创建一个包含所有状态值和组件的常量,例如

const components = {
    "AddPlayer": <AddPlayer />,
    "ShowPlayers": <Players />,
    "Something1": <Something1 />,
    "Something2": <Something2 />
}
Run Code Online (Sandbox Code Playgroud)

将值设置为状态

showComponent(componentName) {
  this.setState({displayedTable: componentName});
}
Run Code Online (Sandbox Code Playgroud)

并在里面简单地渲染

render(){
    return(
        <div>
            {components[this.state.displayedTable]}
        </div>
    )
}
Run Code Online (Sandbox Code Playgroud)

使用 Switch 案例

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

render () {
    return (
        <div>
            { this.renderComponent() }
        </div>
    )
}
Run Code Online (Sandbox Code Playgroud)