反应useState钩子没有按需更新状态

时间:2020-05-15 13:42:14

标签: javascript reactjs react-hooks react-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>
  );
}

2 个答案:

答案 0 :(得分:1)

您应该改用onMouseEnteronMouseLeave事件。

尝试以下操作:

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

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

我希望这会有所帮助!

答案 1 :(得分:-1)

  1. 您应该使用“ debounce”来延迟mouseOver事件的过程。您可以引用以下链接:https://levelup.gitconnected.com/debounce-in-javascript-improve-your-applications-performance-5b01855e086
  2. Lodash库支持去抖动功能。易于使用: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>
  );
}