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

时间:2021-03-20 15:11:55

标签: html reactjs button react-hooks settimeout

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

我有这个

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

到目前为止。

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

5 个答案:

答案 0 :(得分:1)

timeout里面添加useEffect,并传入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

答案 1 :(得分:0)

这样应该可以工作:

<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

答案 2 :(得分:0)

让我们使用useEffect:

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

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

答案 3 :(得分:0)

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

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

答案 4 :(得分:0)

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

在我从函数中获得更新按钮标题后,我只是使用 setTimeout 使它发生了 1 秒的更改。

相关问题