【发布时间】:2022-01-04 01:28:04
【问题描述】:
我正在编写一些代码来将随机颜色映射到行中的单元格。
const COLORS = ['blue', 'green', 'orange', 'red', 'purple', 'yellow'];
const createRandomColors = () => {
const randomColors = [];
for (let i = 0; i < COLORS.length; i++) {
const randomColor = COLORS[Math.floor(Math.random() * COLORS.length)];
randomColors.push(randomColor);
}
return randomColors;
}
const App = () => {
const row = useMemo(createRandomColors, []);
console.log(row);
const cells = useMemo(() => row.map((cell, cellIndex) =>
<div key={cellIndex} style={{ backgroundColor: cell }}>{cellIndex}</div>
), [row]);
cells.forEach(cell => console.log(cell.props.style.backgroundColor));
return (
<div className="app">
<div className="row">
{cells}
</div>
</div>
);
};
export default App;
问题在于,在渲染 div 元素后,它们具有完全不同的内联样式背景颜色,这是在映射 div 时指定的。
请查看CodeSandBox 并查看控制台日志和呈现的真实结果。 为什么会这样?
【问题讨论】: