在单击按钮时切换组件 [英] Toggle component in react on button click

查看:122
本文介绍了在单击按钮时切换组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have 4 components. I only want to render one at a time. I have buttons in my nav, when i click one it should render that component and then hide the other 3 (i.e. set them to null)

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

This is easy with 2 components. I just have a toggle function like so:

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

我现在尝试将其改编为:

I have tried to adapt this for now where I have this:

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

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

This currently shows the component when i click the corresponding button. However, it wont hide the component once the same button is clicked again.

我让我所有的按钮都像下面这样调用此方法:

I have all my buttons calling this method like so:

<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
            }


推荐答案

您可以通过多种方式进行操作,

You can do this in multiple ways,

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

One way is, create a const with all state values and components like

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>
    )
}

这篇关于在单击按钮时切换组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆