React Hooks 在点击时更改按钮的文本然后再次返回

React Hooks Change Text of Button on Click and then back again

使用 React Hooks 我想在用户点击它说“已添加”时更改按钮的文本,然后我想在 1 秒后将其设置回原始文本“添加到购物车”。我假设我会为此使用 setTimeout,但在这种情况下无法弄清楚如何使用它。

我有这个

  const [buttonText, setButtonText] = useState("Add To Cart");

到此为止。

  <button
    type="submit"
    onClick={() => setButtonText("Added")}
  >
    {buttonText}
  </button>

这种方式应该可行:

<button
   type="submit"
   onClick={() => {
   setButtonText("Added");
   setTimeout(() => {
     setButtonText("Add To Cart");
      }, 1000);
     }}
   >
    {buttonText}
 </button>

举个例子:https://codesandbox.io/s/react-hooks-change-text-of-button-on-click-and-then-back-again-qhbzv?file=/src/App.js

让我们使用useEffect:

useEffect(() => {
  const timeout = window.setTimeout(() => {
    setButtonText("Add To Cart")
  }, 1000)

  return () => window.clearTimeout(timeoutID )
}, [buttonText])

只需将 onClick 处理程序更改为此

onClick={
setButtonText("Added");
setTimeout(() => setButtonText("Add to Cart"), 1000)
}

这是我做的解决方案https://codesandbox.io/s/objective-kilby-nicm4?file=/src/App.js

在我从函数中获得更新按钮标题后,我只是使用 setTimeout 将其更改为 1 秒。

useEffect里面添加timeout,并传入buttonText作为依赖,每次更新buttonText,超时都会恢复默认的text值:

const text = "Add To Cart" 
const [buttonText, setButtonText] = useState(text);

 useEffect(()=> {
    const timer = setTimeout(()=> {
       setButtonText(text);
    }, 1000);
    return ()=> clearTimeout(timer);
 }, [buttonText])
 
 return (<button
    type="submit"
    onClick={() => setButtonText("Added")}
  >
    {buttonText}
  </button>)

Working example