首页 > 解决方案 > 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>
  );
}

标签: javascriptreactjsreact-hooksreact-state

解决方案


您应该使用而不是onMouseEnteronMouseLeave事件。

尝试如下:

<button style={{ backgroundColor: buttonColor }}
        onClick={handleClick}
        onMouseEnter={mouseOver}
        onMouseLeave={mouseOut} >

在 React 文档中进一步阅读鼠标事件

我希望这有帮助!


推荐阅读