我对使用 React 构建网站还很陌生,并且在尝试弄清楚如何在单击单选按钮时动态更改 div 的背景时遇到了一些问题。
在我最近尝试获取我想要完成的任务的单元示例时,我生成了以下代码:
const statuses = {
"submitted": "blue"
}
style = {
backgroundColor: "red"
}
render() {
return (
<div className="Employer">
<h2>Employer</h2>
<div className="status-wrapper">
<div className="status-option">
<input type="radio" value="progress" name="option" onChange={e => this.style['backgroundColor'] = statuses[e.target.value]} style={this.style}></input>
<label>In Progress</label>
</div>
</div>
</div>
);
}
我的主要组成部分以及状态如下:
state = {
postings: [{
id: 1,
style: {backgroundColor: 'yellow'},
name: "Google",
status: 0
}]
}
render(){
return (
<div className="App">
<Employer postings = {this.state.postings}></Employer>
</div>
);
}
代码会导致“TypeError: 'backgroundColor' is read-only”错误,我想这可能是由于未正确更新组件状态造成的。
如果有人可以帮助我解决这个问题,并希望帮助我在此过程中了解更多有关 React 的信息,我将非常感激!
最佳答案
您正在更新 this.style
不是状态对象。因此请使用 this.setState()
函数调用。并且还可以使用 this.state 更改样式.style
Changer = e => {
let val = e.target.value;
this.setState(state => {
state.style.backgroundColor = statuses[val];
return state;
});
};
对于输入侧
<input type="radio"
value="progress"
name="option"
onChange={this.Changer}
style={{ ...this.state.style }}
/>
<label style={{ ...this.state.style }}>In Progress</label>
检查这个 Sandbox
- 如果您使用类,首先要做的就是使用构造函数而不是普通的
状态
- 您正在设置输入单选按钮的颜色。但颜色不可见。所以用标签修复它的工作
- 要更改整个对象的样式,请使用扩展运算符将对象复制到元素的样式
{...object}
关于javascript - ReactJS - 单击单选按钮时动态更改组件的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58744200/