[英]Change style dynamically, without resetting when re-rendered in React
I have a page of just a list of divs calling an onClick function.我有一个页面,其中只有一个调用 onClick 函数的 div 列表。 Pretty much this...
差不多这个...
<div
className="square card-container bg-primary"
points="200"
id="2"
onClick={e => select(200, "cat1", e.target.id)}
>
<h3 className="text-light">200</h3>
</div>
Just 30 of them.只有 30 个。 With sequential ID's.
带有顺序 ID。 It's easy enough to push the ID's to a new array when clicked, or to add className once they're clicked, and when I step through the code in Debugger I can see that the class is Added and the styles change, but it is immediately set back to the previous "Un-clicked" className.
单击时将 ID 推送到新数组很容易,或者在单击后添加 className,当我在调试器中逐步执行代码时,我可以看到类已添加且样式已更改,但它是立即设置回之前的“未单击”类名。 I was thinking that it might work to make each of these div it's own component and than use useState, but since they're all mostly identical I would still need a key or id, so I'm not sure how I would pass that in to a state and use that conditionally?
我在想将这些 div 中的每一个都变成自己的组件而不是使用 useState 可能会起作用,但是由于它们几乎都是相同的,我仍然需要一个键或 id,所以我不确定我将如何传递它到一个状态并有条件地使用它? I'm sorry if this doesn't make sense.
如果这没有意义,我很抱歉。 Basically I just want to change styles slightly once an item has been selected, without going back to the initial className when it is re-rendered.
基本上,我只想在选择一个项目后稍微更改样式,而不在重新渲染时返回初始 className。 This is the script that gets called onClick.
这是调用 onClick 的脚本。
const selected = []
const change = id => {
selected.push(id);
console.log(selected);
};
const select = (points, cat, id) => {
let newArr = questions.filter(
q => q.category === "Sample 1" && q.points === points
);
change(id);
if (newArr.length > 1) {
let randomOutput = Math.floor(Math.random() * newArr.length);
console.log(newArr[randomOutput]);
let out = newArr[randomOutput];
props.setQuestion({ out });
props.detail();
return out;
} else {
let out = newArr;
props.setQuestion({ out });
props.detail();
console.log(points, cat);
}
}
You need to store a list of selected items using state and make className
dynamic您需要使用 state 存储所选项目的列表并使
className
动态化
Example: https://jsfiddle.net/78bsnhgw/示例: https : //jsfiddle.net/78bsnhgw/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.