【发布时间】:2020-06-27 23:03:02
【问题描述】:
我正在使用 React 创建一个组件,该组件将根据其属性呈现不同的背景。但是,我不知道如何在不折叠 React 框架的情况下更改其属性。 这是我的代码:
const inactiveStyle = {
backgroundColor: "",
color: "white",
};
const activeStyle = {
color: "black"
};
export default class DrumPad extends Component {
constructor(props) {
super(props);
this.state = {
style: inactiveStyle,
};
render(){
inactiveStyle.backgroundColor = this.props.backgroundColor
return (<div style={this.state.style}></div>)
当我尝试时,这是我得到的错误:
TypeError:无法分配给对象“#”的只读属性“backgroundColor”
我已经尝试遵循here 的建议,但它不起作用,因为我的原始代码已经是常量,而不是状态本身。请帮忙。
【问题讨论】:
-
你想用这条线
inactiveStyle.backgroundColor = this.props.style达到什么目的? -
@Siddharth 在我的道具中,有一个特定的背景颜色值,我只想添加到我的 inactiveStyle(而不是我的 activeStyle)。因此,我仍然希望状态样式存在
-
对象是引用,所以你实际上是在改变当前的状态对象。 Do not mutate the state.
-
@EmileBergeron 不幸的是,不,我知道我不应该直接改变状态,但我不知道如何使用设置状态更改背景颜色
标签: javascript html reactjs react-props react-state