【发布时间】:2021-04-04 09:42:09
【问题描述】:
我试图弄清楚如何解决一个应用 useState 钩子概念的颜色框练习。给定一个包含 12 种不同颜色的数组,最初状态将显示 12 个具有相应颜色的 div。单击按钮后,只有随机选择的 div 会更改为随机颜色(在 12 种给定颜色中),并在 div 上使用“已更改”消息标记该 div。到目前为止,我能够使颜色框容器在 div 上显示每种颜色。每次单击时,我都会看到状态变为随机颜色。但我不知道如何只制作随机 div 来更改颜色并显示消息。这个问题是否需要每个颜色的唯一 id 来跟踪状态的变化?
import React, { useState } from 'react';
import ColorBox from './ColorBox';
import {choice} from './colorHelpers';
const ColorBoxes = () => {
const [ boxes, setBoxes] = useState(colors);
const [msg, setMsg] = useState(null);
const clickHandler = () => {
setBoxes(()=>choice(colors));
setMsg('changed');
};
return (
<>
{colors.map((color,i) =>{
return(
<div>
<ColorBox key={i} color={color} />{color}
</div>
);
})}
<button onClick={clickHandler}>Change Color!</button>
</>
);
};
import React from 'react';
import './ColorBox.css';
const ColorBox = ({ color }) => {
return <div className="colorBox" style={{ backgroundColor: color }} />;
};
export default ColorBox;
const choice = (arr) => {
const randIdx = Math.floor(Math.random() * arr.length);
return arr[randIdx];
};
export { choice };
【问题讨论】: