繁体   English   中英

反应 useState 钩子没有根据需要更新 state

[英]React useState hook isn't updating state as desired

我正在尝试将按钮的背景颜色更改为黑色,因为鼠标 hover 在它上面并在它不是时将其更改回白色。 我在一个字符串上使用了 state ,该字符串将变为黑色或白色,并将其传递给 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>
  );
}

您应该改用onMouseEnteronMouseLeave事件。

尝试如下:

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

进一步阅读鼠标事件的 React 文档。

我希望这有帮助!

  1. 您应该使用“去抖动”来延迟 mouseOver 事件的过程。 可以参考链接: https://levelup.gitconnected.com/debounce-in-javascript-improve-your-applications-performance-5b01855e086
  2. Lodash 库支持去抖 function。 它易于使用: https://lodash.com/docs/4.17.15#debounce

导入反应,{ 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>
  );
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM