【发布时间】:2022-11-29 06:05:34
【问题描述】:
所以我想渲染 x 个圆圈。每个圆圈都呈现在屏幕上的随机位置。它们中的每一个都有一个值参数,这是将添加到左上角显示的总点数的数量。单击一个圆圈后,它应该将其值添加到计数中并消失。它做了它应该做的事情,但是在点击时,所有其他圆圈都会重新呈现一个新的随机位置,这是他们不应该做的。初始设置的 x 和 y 位置应该为每个圆圈生成一次并保持这样。我如何防止这种情况发生? 这是我的代码:
import { useState } from "react";
import "./App.css";
function App() {
const [count, setCount] = useState(0);
let ctr = 0;
function getRandom(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min) + min);
}
function renderCircle(xPos, yPos, color, value) {
ctr++;
const handleClick = (id) => () => {
setCount(count + value);
const el = document.getElementById(id);
el.style.visibility = "hidden";
};
return (
<div>
{
<svg
className="circle"
id={ctr}
onClick={handleClick(ctr)}
style={{
left: `calc(${xPos}vw - 60px)`,
top: `calc(${yPos}vw - 60px)`,
position: "absolute",
}}
>
<circle cx={30} cy={30} r={30} fill={color} />
</svg>
}
</div>
);
}
function renderCircles(amount) {
const arr = [];
for (let i = 0; i < amount; i++) {
let circle = renderCircle(
getRandom(3, 53),
getRandom(3, 40),
Object.keys(Color)[
Math.floor(Math.random() * Object.keys(Color).length)
],
getRandom(1, 100)
);
arr.push(circle);
}
return arr;
}
return (
<div className="App">
<div className="App-game">{renderCircles(15)}</div>
<div className='App-currency' style={{color: "black", fontSize: 80}}>
{count}
</div>
</div>
);
}
export default App;
class Color {
static Green = new Color("green");
static Blue = new Color("blue");
static Yellow = new Color("yellow");
static Red = new Color("red");
static Pink = new Color("pink");
static Orange = new Color("orange");
constructor(name) {
this.name = name;
}
toString() {
return `Color.${this.name}`;
}
}
【问题讨论】:
标签: javascript reactjs