createRef 每次渲染都会返回一个新的引用,而 useRef 每次都会返回相同的引用。看代码:
const App = ()=>{
const [renderIndex,setRenderIndex] = useState(1);
const refFromUseRef = useRef();
const refFromCreateRed = createRef();
if (!refFromUseRef.current){
refFromUseRef.current=renderIndex
}
if (!refFromCreateRed.current) {
refFromCreateRed.current = renderIndex
}
return <>
<p>index {renderIndex}</p>
<p>refFromUseRef {refFromUseRef.current}</p>
<p>refFromCreateRed {refFromCreateRed.current}</p>
<button onClick={() => { setRenderIndex(p=>p+1)}}>a</button>
</>
}
ReactDOM.render(
<App />,
document.getElementById('root')
);
手动实现createRef和useRef的建议代码如下:
const createRef = ()=>{
return { current: null }
}
let obj = { current: null }
const useRef = ()=>{
return obj
}
再看一个例子:
const App = ()=>{
const [count, setCount] = useState(0);
function handleAlertClick(){
setTimeout(()=>{
alert(count)
},3000);
}
return <div>
<p>你点击了{count}次</p>
<button onClick={()=>setCount(count+1)}>click me</button>
<button onClick={handleAlertClick}> show Alert</button>
</div>
}
ReactDOM.render(
<App />,
document.getElementById('root')
);
点击第一个按钮连续点击,在点击过程中顺便点击Alert按钮,此时发现弹出的数字和count不同步,该如何呢?
const App = ()=>{
const [count, setCount] = useState(0);
const lastCount = useRef(count);
useEffect(()=>{
lastCount.current = count;
})
function handleAlertClick(){
setTimeout(()=>{
alert(lastCount.current)
},3000);
}
return <div>
<p>你点击了{count}次</p>
<button onClick={()=>setCount(count+1)}>click me</button>
<button onClick={handleAlertClick}> show Alert</button>
</div>
}
ReactDOM.render(
<App />,
document.getElementById('root')
);
此时count的值会显示最终的count值了。上面的代码,我们将lastCount.current指向count,这样在访问lastCount.current
时就会访问最新的count。
以上便是createRef和useRef的区别了,希望对你有所帮助。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。