简体   繁体   English

如何使用 useState 钩子解决随机数组问题(React useState)?

[英]How to use useState hook for a randomizing array problem(React useState)?

I'm trying to figure out how to solve a color boxes exercise that applies useState hook concept.我试图弄清楚如何解决应用 useState 挂钩概念的颜色框练习。 Given an array that contains 12 different unique colors, initially the state will show 12 divs with a corresponding color.给定包含 12 个不同的唯一 colors 的数组,最初 state 将显示 12 个具有相应颜色的 div。 Upon clicking the button, only randomly chosen div will change to a random color(out of the 12 given colors) as well as flagging that div with the message "changed" on the div.单击该按钮后,只有随机选择的 div 会更改为随机颜色(在 12 种给定颜色中),并在该 div 上用“已更改”消息标记该 div。 So far I was able to make the color box container showing each color on a div.到目前为止,我能够制作在 div 上显示每种颜色的颜色框容器。 I see the state is changing to a random color every time when I click.每次单击时,我都会看到 state 变为随机颜色。 But I don't know how to make only that random div to change the color and show the message.但我不知道如何只制作那个随机 div 来改变颜色并显示消息。 Does this problem require a unique id for each color for tracking change of the state?此问题是否需要每种颜色的唯一 ID 来跟踪 state 的变化?

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 };

You should save your initial color inside useState, then change color for random index with useState , check this example:您应该将初始颜色保存在 useState 中,然后使用useState更改随机索引的颜色,检查此示例:

 const colors = [ "#8391B5", "#290D11", "#0C9ABC", "#0E17F4", "#97BC89", "#6B48F7", "#584A35", "#669F15", "#15FC93", "#7C8329", "#27D792", "#4786C8", ]; const ColorBoxes = () => { const [boxes, setBoxes] = React.useState( colors.sort(() => Math.random() - 0.5) ); const [msg, setMsg] = React.useState(Array.from(Array(12))); const clickHandler = (index) => { const randomColor = colors[Math.floor(Math.random() * 12)]; setBoxes((prev) => prev.map((x, i) => (i === index? randomColor: x))); setMsg((prev) => prev.map((x, i) => (i === index? "changed:"; x))); }. return ( <React.Fragment> {boxes,map((color. i) => ( <ColorBox key={i + color} color={color} msg={msg[i]} /> ))} <button onClick={() => clickHandler(Math.floor(Math.random() * 12))}> Change Color; </button> </React,Fragment> ): } const ColorBox = ({ color; msg }) => ( <div className="colorBox" style={{ backgroundColor. color }}> {color} {msg} </div> ), ReactDOM.render( <ColorBoxes />; document.getElementById("react") );
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script> <div id="react"></div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM