切换组件对按钮单击做出反应
Toggle component in react on button click
我有 4 个组成部分。我只想一次渲染一个。我的导航栏中有按钮,当我单击一个按钮时,它应该渲染该组件,然后隐藏其他 3 个(即将它们设置为 null)
只需 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
}
您可以通过多种方式执行此操作,
一种方法是,创建一个包含所有状态值和组件的常量,例如
const components = {
"AddPlayer": <AddPlayer />,
"ShowPlayers": <Players />,
"Something1": <Something1 />,
"Something2": <Something2 />
}
将值设置为类似
的状态
showComponent(componentName) {
this.setState({displayedTable: componentName});
}
并在内部简单渲染
render(){
return(
<div>
{components[this.state.displayedTable]}
</div>
)
}
使用 Switch case
renderComponent(){
switch(this.state.displayedTable) {
case "AddPlayer":
return <AddPlayer />
case "ShowPlayers":
return <Players />
}
}
render () {
return (
<div>
{ this.renderComponent() }
</div>
)
}
我有 4 个组成部分。我只想一次渲染一个。我的导航栏中有按钮,当我单击一个按钮时,它应该渲染该组件,然后隐藏其他 3 个(即将它们设置为 null)
只需 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
}
您可以通过多种方式执行此操作,
一种方法是,创建一个包含所有状态值和组件的常量,例如
const components = {
"AddPlayer": <AddPlayer />,
"ShowPlayers": <Players />,
"Something1": <Something1 />,
"Something2": <Something2 />
}
将值设置为类似
的状态showComponent(componentName) {
this.setState({displayedTable: componentName});
}
并在内部简单渲染
render(){
return(
<div>
{components[this.state.displayedTable]}
</div>
)
}
使用 Switch case
renderComponent(){
switch(this.state.displayedTable) {
case "AddPlayer":
return <AddPlayer />
case "ShowPlayers":
return <Players />
}
}
render () {
return (
<div>
{ this.renderComponent() }
</div>
)
}