使用 React Hooks 我想在用户单击按钮说“添加”时更改按钮的文本,然后我想在 1 秒后将其设置回原始文本“添加到购物车”。我想我会为此使用 setTimeout,但我无法弄清楚在这种情况下如何使用它。
我有这个
const [buttonText, setButtonText] = useState("Add To Cart");
到目前为止。
<button
type="submit"
onClick={() => setButtonText("Added")}
>
{buttonText}
</button>
答案 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>)
答案 1 :(得分:0)
这样应该可以工作:
<button
type="submit"
onClick={() => {
setButtonText("Added");
setTimeout(() => {
setButtonText("Add To Cart");
}, 1000);
}}
>
{buttonText}
</button>
答案 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 秒的更改。