[英]react fails to inline change the background color of a button
I am trying to inline toggle the background color of the submit button with react and state. I am aware that this can be achieved through a bool value isMouseOver? "black": "white"
我正在尝试使用 react 和 state 内联切换提交按钮的背景颜色。我知道这可以通过 bool 值isMouseOver? "black": "white"
isMouseOver? "black": "white"
in style. isMouseOver? "black": "white"
。 But I wonder why my first attempt does not work?但我想知道为什么我的第一次尝试不起作用? Even though the variable myColor
has been changed by my mouse action:即使变量myColor
已被我的鼠标操作更改:
import React, { useState } from "react";
function App() {
const [myColor, setColor] = useState("white");
function toggleColor() {
if (myColor === "black") {
setColor("white");
} else {
setColor("black");
}
console.log("mycolor", myColor);
}
return (
<div className="container">
<h1>{myColor}</h1>
<input type="text" placeholder="What's your name?" />
<button
style={{ backgroundColor: { myColor } }}
onMouseOver={toggleColor}
onMouseOut={toggleColor}
>
Submit
</button>
</div>
);
}
export default App;
just change this line ie remove the curly braces around myColor
, it should working fine只需更改此行,即删除myColor
周围的花括号,它应该可以正常工作
style={{ backgroundColor: { myColor } }}
to到
style={{ backgroundColor: myColor }}
I am trying to inline toggle the background color of the submit button with react and state.我正在尝试使用 react 和 state 内联切换提交按钮的背景颜色。 I am aware that this can be achieved through a bool value isMouseOver? "black": "white"
我知道这可以通过布尔值isMouseOver? "black": "white"
isMouseOver? "black": "white"
in style. isMouseOver? "black": "white"
。 But I wonder why my first attempt does not work?但我想知道为什么我的第一次尝试不起作用? Even though the variable myColor
has been changed by my mouse action:即使变量myColor
已被我的鼠标操作更改:
import React, { useState } from "react";
function App() {
const [myColor, setColor] = useState("white");
function toggleColor() {
if (myColor === "black") {
setColor("white");
} else {
setColor("black");
}
console.log("mycolor", myColor);
}
return (
<div className="container">
<h1>{myColor}</h1>
<input type="text" placeholder="What's your name?" />
<button
style={{ backgroundColor: { myColor } }}
onMouseOver={toggleColor}
onMouseOut={toggleColor}
>
Submit
</button>
</div>
);
}
export default App;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.