javascript - 不能用“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 得到相同的结果呢?
解决方案
使用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>
推荐阅读
- postgresql - 如何将带有点作为千位分隔符的 CSV 文件导入 PostgreSQL
- c# - 将模型传递给 _Layout.cshtml(webapp 版本)
- python - 如何使用气泡图可视化 5-D 混合数据?
- javascript - $.get 不是函数,不推荐使用主线程上的同步 XMLHttpRequest
- r-markdown - R Markdown beamer 演示文稿类似引用
- sql - Oracle SQL 三元运算符或函数?
- javascript - 带有查找的 NodeJS Mongodriver 聚合使不需要的内部连接
- c++ - c++协程连续循环导致堆栈溢出
- mysql - 如何在 MySQL 的约束中检查外键引用的记录的值
- c - 如何在C中调用单链表中的字符串