React useState 挂钩未按需更新状态

React useState hook isn't updating state as desired

我正在尝试将鼠标悬停在按钮上的按钮的背景颜色更改为黑色,然后在鼠标悬停在按钮上时将其更改回白色。我在将变为黑色或白色的字符串上使用状态,并以样式 属性 传递它。知道我哪里出错了吗?

谢谢。

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>
  );
}

您应该改用 onMouseEnteronMouseLeave 事件。

尝试如下:

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

在此处进一步阅读 Mouse Events 的 React 文档。

希望对您有所帮助!

  1. 你应该使用"debounce"来延迟mouseOver事件的进程。您可以参考link:https://levelup.gitconnected.com/debounce-in-javascript-improve-your-applications-performance-5b01855e086
  2. Lodash库支持debounce功能。使用方便:https://lodash.com/docs/4.17.15#debounce

从 "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>
  );
}