【问题标题】:Type Error: Cannot assign to read only property 'backgroundColor' of object '#<Object>'类型错误:无法分配给对象“#<Object>”的只读属性“backgroundColor”
【发布时间】: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 达到什么目的?
  • 这能回答你的问题吗? How to update nested state properties in React
  • @Siddharth 在我的道具中,有一个特定的背景颜色值,我只想添加到我的 inactiveStyle(而不是我的 activeStyle)。因此,我仍然希望状态样式存在
  • 对象是引用,所以你实际上是在改变当前的状态对象。 Do not mutate the state.
  • @EmileBergeron 不幸的是,不,我知道我不应该直接改变状态,但我不知道如何使用设置状态更改背景颜色

标签: javascript html reactjs react-props react-state


【解决方案1】:

我觉得这里根本不需要 state,因为它基于 props 值或默认值。

const DrumPad = ({ backgroundColor, ...props }) => (
  <div
    style={{
      backgroundColor,
      color: 'white',
    }}
  >
    ...
  </div>
);

您尚未共享所有相关代码,但如果您想打开一些 isActive 道具,您仍然可以这样做:

const inactiveStyle = { color: 'white' };
const activeStyle = { color: 'black' };

const DrumPad = ({ isActive, backgroundColor, ...props }) => (
  <div
    style={{
      ...(isActive ? activeStyle : inactiveStyle),
      backgroundColor
    }}
  >
    ...
  </div>
);

如果出于某种原因,您仍想使用组件的状态,请复制默认样式对象和use the props to initialize the state,然后使用this.setState 对其进行更新。

请注意,以下代码根本没有任何好处,我只是将它放在一起作为setState API 工作原理的示例。

const inactiveStyle = { color: 'white' };
const activeStyle = { color: 'black' };

class DrumPad extends Component {
  state = {
    isActive: false,
    style: {
      ...inactiveStyle,
      backgroundColor: this.props.backgroundColor
    }
  }

  onClick = () => {
    // toggle the active state and style.
    this.setState(({ style, isActive }) => ({
      isActive: !isActive,
      style: {
        ...style,
        ...(!isActive ? activeStyle : inactiveStyle),
      },
    }));
  }

  render() {
    return (
        <div style={this.state.style} onClick={this.onClick}>
          ...
        </div>
      );
  }
}

如果您希望在 props 和之前的任何状态发生变化时更新状态,现在可以使用 getDerivedStateFromProps

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-12
    • 2019-04-27
    • 2021-06-17
    • 2019-08-30
    • 2023-03-13
    • 2021-09-26
    相关资源
    最近更新 更多