javascript - React useState 钩子没有根据需要更新状态
问题描述
当鼠标悬停在按钮上时,我正在尝试将按钮的背景颜色更改为黑色,并在没有时将其更改回白色。我在字符串上使用了状态,该状态将变为黑色或白色,并将其传递给 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>
);
}
解决方案
您应该使用而不是onMouseEnter
和onMouseLeave
事件。
尝试如下:
<button style={{ backgroundColor: buttonColor }}
onClick={handleClick}
onMouseEnter={mouseOver}
onMouseLeave={mouseOut} >
在 React 文档中进一步阅读鼠标事件。
我希望这有帮助!
推荐阅读
- ios - Info.plist 中的 UIRequiredDeviceCapabilities 键设置为应用程序不会安装在 iPad 上
- java - 我手机中的这个应用商店笔记在它第一次运行时运行它,然后我单击添加按钮并且应用程序崩溃。从手机加载应用程序数据的问题
- json - 如何读取包含许多下级的 pandas 数据帧复杂 JSON 文件
- python - Python请求接收状态码400中的问题
- node.js - 如何将整数值作为 JSON 后值发送并在 express JS 文件中处理?
- javascript - 有没有办法使用 Javascript 显示此幻灯片上的最后一张图片?
- javascript - 努力兑现承诺
- vim - FZF之类的快速切换到目录的方式?在 Vim FZF 中包含隐藏文件?
- android - 关闭所有用户会话 Android Firebase
- java - 在绘画面板上添加消息框