提问者:小点点

React钩子在单击时更改按钮的文本,然后再返回


使用React钩子,我想改变我的按钮的文本,当用户点击它说“添加”,然后我想设置回原来的文本“添加到购物车”后1秒。我假设我会为此使用setTimeout,但在这种情况下,我很难弄清楚如何使用它。

我有这个

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

到目前为止。

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

共2个答案

匿名用户

这样就应该起作用:

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

这里有一个示例:https://codesandbox.io/s/react-hooks-chang-text-of-button-on-click-and-then-back-again-qhbzv?file=/src/app.js

匿名用户

只需将onclick处理程序更改为

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