我是React的新手,尝试根据状态变量加载不同的组件。我希望我的处理程序动态地知道我正在更新哪个状态变量。到目前为止,我将显式地将状态名称作为字符串传递。
状态变量
state = {
showLogin: false,
showHome: false
}
处理程序方法
handleShow = (element) => this.setState({ element: true });
按钮
{
!this.props.isAuthenticated ? (
<Button
variant="outline-primary"
onClick={() => this.handleShow("showLogin")}
>
Login
</Button>
) : (
<>
<Button
variant="outline-primary"
onClick={() => this.handleShow("showHome")}
>
Home
</Button>
<Button variant="outline-primary" onClick={this.authorizeUserMethod}>
LogOut
</Button>
</>
);
}
尝试这个
handleShow = element => this.setState({
...this.state,
[element]: true
});
在处理程序方法中,必须使用spread运算符,这样可以创建状态的克隆,从而连接新值。
处理程序方法
handleShow = (element) => this.setState({ ...this.state, [element]: true });