useRef
是一個(gè) React Hook,它能讓你引用一個(gè)不需要渲染的值。
點(diǎn)擊計(jì)時(shí)器
點(diǎn)擊按鈕后在控制臺可以打印但是頁面不生效。
useRef
返回的值在函數(shù)組件中不會自動觸發(fā)重新渲染,所以控制臺可以顯示變化而按鈕上無法顯示 ref.current
的變化。
import { useRef } from "react";
const ClinkNumber = () => {
let ref = useRef(0);
function handleClick() {
ref.current = ref.current + 1;
// 每次觸發(fā)函數(shù)會跟隨變動 +1
console.log(ref.current);
}
return (
<div>
// ref.current 不會跟隨變動
<button onClick={handleClick}>點(diǎn)擊計(jì)時(shí)器 {ref.current}</button>
</div>
);
};
export default ClinkNumber;
解決這個(gè)問題的方法是使用 React 的狀態(tài)管理來保存并更新計(jì)數(shù)器的值。文章來源:http://www.zghlxwxcb.cn/news/detail-693865.html
const [counter, setCounter] = useState(0);文章來源地址http://www.zghlxwxcb.cn/news/detail-693865.html
到了這里,關(guān)于useRef 定義的 ref 在控制臺可以打印但是頁面不生效?的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!