San*_*taz 1 reactjs material-ui react-component
我是 React JS 的新手。我有多个图标按钮。OnClick 我只想让单击的按钮更改其颜色。我使用了状态,但是当状态改变时,所有按钮的颜色都会改变。我应该采用什么方法?有没有一种方法可以在不使用状态的情况下改变颜色?需要钥匙或身份证吗?我提供的代码已被裁剪(意味着它仅包含我认为相关的部分)。
class Utilitybar extends React.Component {
constructor(props) {
super(props);
this.state = {
bgColor: "default"
};
}
render() {
return (
<div>
<IconButton color={
this.state.bgColor
}
onClick={
() => {
this.props.vidToggle();
if (this.state.bgColor === "default") {
this.setState({ bgColor: "primary" })
} else {
this.setState({ bgColor: "default" })
}
}
}>
<FaPlayCircle />
</IconButton>
<IconButton color={
this.state.bgColor
}
onClick={
() => {
this.props.fileToggle();
if (this.state.bgColor === "default") {
this.setState({ bgColor: "primary" })
} else {
this.setState({ bgColor: "default" })
}
}
}>
<FaRegFileAlt />
</IconButton>
</div>
);
}
}
Run Code Online (Sandbox Code Playgroud)
我希望只有点击按钮才能改变颜色。但显然它们都使用相同的状态,当状态改变时,所有按钮的颜色都会改变。
不要存储共享属性(背景颜色),而是存储您真正需要的信息:即按下的按钮
class Utilitybar extends React.Component {
constructor(props) {
super(props)
this.onButtonClicked = this.onButtonClicked.bind(this)
this.state = { currentButton: null }
}
onButtonClicked (id) {
this.setState({ currentButton: this.state.currentButton === id ? null : id })
}
render(){
return (
<div>
<IconButton
color={this.state.currentButton === 0 ? "primary" : "default" }
onClick={() => this.onButtonClicked(0)}>
<FaPlayCircle/>
</IconButton>
<IconButton
color={this.state.currentButton === 1 ? "primary" : "default" }
onClick={() => this.onButtonClicked(1)}>
<FaRegFileAlt/>
</IconButton>
</div>
);
}
}
Run Code Online (Sandbox Code Playgroud)
编辑:这个想法是存储与您的一个按钮相对应的 ID(请注意,我假设一次只能单击一个按钮)。该ID被放入组件状态中。然后每个按钮都会根据状态中的 ID 检查其 ID;如果匹配,则会呈现不同的背景。由于您可能希望在第二次单击后取消按下按钮,因此 onButtonClicked 在更新状态之前会检查当前 ID,如果它与新 ID 相同,则会清除存储的 ID
| 归档时间: |
|
| 查看次数: |
4150 次 |
| 最近记录: |