我正在尝试将鼠标悬停在按钮上方时将按钮的背景色更改为黑色,而在没有按钮时将其更改为白色。我在字符串上使用了状态,该状态将变为黑色或白色,并将其传递给style属性。对我要去哪里错有任何想法吗?
谢谢。
import React, { useState } from "react";
function App() {
const [headingText, setHeadingText] = useState("Hello");
const [buttonColor, setButtonColor] = useState("White"); //setting the state
function handleClick() {
setHeadingText("Submitted");
}
function mouseOver() {
setButtonColor("Black"); //changing state
}
function mouseOut() {
setButtonColor("White"); //changing state
}
return (
<div className="container">
<h1>{headingText}</h1>
<input type="text" placeholder="What's your name?" />
<button
style={{ backgroundColor: { buttonColor } }} //where I want it to apply
onClick={handleClick}
onMouseOver={mouseOver}
onMouseOut={mouseOut}
>
Submit
</button>
</div>
);
}
答案 0 :(得分:1)
您应该改用onMouseEnter
和onMouseLeave
事件。
尝试以下操作:
<button style={{ backgroundColor: buttonColor }}
onClick={handleClick}
onMouseEnter={mouseOver}
onMouseLeave={mouseOut} >
在此处进一步阅读Mouse Events的React文档。
我希望这会有所帮助!
答案 1 :(得分:-1)
从“ react”导入React,{useState};
import { debounce } from 'lodash';
function App() {
const [headingText, setHeadingText] = useState("Hello");
const [buttonColor, setButtonColor] = useState("White"); //setting the state
function handleClick() {
setHeadingText("Submitted");
}
function mouseOver() {
setButtonColor("Black"); //changing state
}
function mouseOut() {
setButtonColor("White"); //changing state
}
return (
<div className="container">
<h1>{headingText}</h1>
<input type="text" placeholder="What's your name?" />
<button
style={{ backgroundColor: { buttonColor } }} //where I want it to apply
onClick={handleClick}
onMouseOver={debounce(mouseOver, 200)}
onMouseOut={debounce(mouseOut, 200)}
>
Submit
</button>
</div>
);
}