有 16 个蓝色框,如果您单击任何框,颜色会变成红色。最多 2 个框可以是红色的,如果您单击任何第三个框,则它会变成红色,第一个红色框会变成蓝色,依此类推...
答案 0 :(得分:0)
import React, { useState } from "react";
import "./style.css";
const Box = ({ onPress, style }) => {
return <div style={style} onClick={onPress} className="box" />;
};
export default function App() {
/*
This is the main part of the app, here we create a state called checked which
will hold the last two indexes of checked boxes, and based on that index,
we will conditionally set the background color of the Box component to either
red or blue.
*/
const [checked, setChecked] = useState([]);
let array = Array.from({ length: 16 }, () => 0);
// console.log(array);
return (
<div className="container">
{array?.map((_, index) => (
<Box
key={index}
onPress={() => {
let temp = [...checked];
if (temp.length === 2) {
temp.shift();
}
if (!temp.includes(index)) setChecked([...temp, index]);
}}
style={{ backgroundColor: checked.includes(index) ? "red" : "blue" }}
/>
))}
</div>
);
}
完整示例:Stackblitz Example