首页 > 解决方案 > 不能用“null”覆盖背景色

问题描述

在我的反应应用程序中,某些子元素的背景颜色是通过 state 的 props 给出的。所有颜色的初始值为 null,因此元素只是透明的。经过一些交互并单击用户可以将状态值更改为其他颜色,以便背景更改。

之后我希望能够将所有颜色设置回 null 但不知何故它不起作用,这是我的代码的一小部分:

 state = { colors: [
              { id: 1, color: null },
              { id: 2, color: null },
              { id: 3, color: null },
              { id: 4, color: null }
                 ]}
 reset = () => {
                let colors = [...this.state.colors]
                colors.forEach(color => color.color = null)
                this.setState({ colors: colors })
                }                        

状态中颜色键的值按预期变回 null,但元素的颜色并没有消失。如果我尝试做类似的事情

 colors.forEach(color => color.color = "red")

那么所有的颜色实际上都变成了红色,但是为什么我不能用 null 得到相同的结果呢?

标签: javascriptreactjsnullstatebackground-color

解决方案


使用transparent而不是null工作。这是一个演示

class Colors extends React.Component {
  
  constructor(props) {
    super(props);
    this.state = { colors: props.colors };
    this.reset = this.reset.bind(this);
  }
  
  reset() {
    const colors = this.state.colors.map(({ id }) => {
      return { id, color: 'transparent' }
    });
    this.setState({ colors });
  }  
 
 render() {
    const colors = this.state.colors;
    return (
      <div>
      {colors.map(({id, color}, i) => {
        return <div key={i} style={{backgroundColor: color}}>{i}</div>
      })}        
      <button onClick={this.reset}>Reset</button>
      </div>
    );
  }
}

const colors = [
  { id: 1, color: 'red' },
  { id: 2, color: 'blue' },
  { id: 3, color: 'green' }
];

ReactDOM.render(
  <Colors colors={colors} />,
  document.getElementById('container')
);
div {
  height: 20px;
  width: 20px;
  color: black;
  margin-bottom: 2px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="container"></div>


推荐阅读