使用React和钩子设置样式
我一直在使用React JS很短的时间。查看以下示例,我想仅在点击线上而不是所有行上更改背景颜色。实际上,单击一排将其变成红色并再次单击使行背景为白色。在更改颜色之前,我将所有线路都设置为默认的颜色状态,但是有些问题。
import { useState } from "react";
export default function App() {
const [color, setColor] = useState("white");
const handleClick = (e) => {
const value_color = e.target.style.backgroundColor;
if (value_color != "" && value_color != undefined) {
if (value_color === "white")
var new_color = "red";
else
var new_color = "white";
}
setColor("white");
e.target.style.backgroundColor = new_color;
};
return (
<div>
<div
id={"line1_id"}
style={{
backgroundColor: color
}}
onClick={handleClick}
>
First Line
</div>
<div
id={"line2_id"}
style={{
backgroundColor: color
}}
onClick={handleClick}
>
Second Line
</div>
</div>
);
}
编辑: 也许我解释了问题错误。实际上,我的代码有效,但是单击两个我都会得到两条红线。通常,当我单击新线路时,另一行应该再次变白。谢谢
I have been using React JS for a short time. Looking at the following example, I would like to change the background color only on the clicked lines and not all lines. Actually, clicking on a row turns it red and clicking again makes the row background white. Before changing color, I would set all lines to default color states, but something is wrong.
import { useState } from "react";
export default function App() {
const [color, setColor] = useState("white");
const handleClick = (e) => {
const value_color = e.target.style.backgroundColor;
if (value_color != "" && value_color != undefined) {
if (value_color === "white")
var new_color = "red";
else
var new_color = "white";
}
setColor("white");
e.target.style.backgroundColor = new_color;
};
return (
<div>
<div
id={"line1_id"}
style={{
backgroundColor: color
}}
onClick={handleClick}
>
First Line
</div>
<div
id={"line2_id"}
style={{
backgroundColor: color
}}
onClick={handleClick}
>
Second Line
</div>
</div>
);
}
EDIT:
Maybe I have explained the problem wrong. Actually my code works, but clicking on both I get two red lines. In general, when I click on a new line, the other line should go white again. Thank you
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我创建了一个npm软件包,可以做到这一点:管理React的CSS变量。
https://github.com/morewings/morewings/css-vars-vars-hook-hook
I created an NPM package which does exactly this: manages CSS variables from React.
https://github.com/morewings/css-vars-hook
为数据创建JSON,并使用
MAP
用于渲染数据并更新backgroundColor
这是 codesandbox示例
Create JSON for the data and use
map
for rendering the data and updating thebackgroundColor
here is the Codesandbox example
new_color
值未定义,因为您将其设置在if-else语句中。因此,只有IF-ELSE块中的代码才能访问它们。您可以声明一个变量并在其外部分配默认值,然后重新分配它:The
new_color
value is not defined because you are setting it in the if-else statements. So, only code in the if-else blocks can access them. You can declare a variable and assign a default value outside them and then reassign it: