useRef
useRef有2个作用:
- 绑定DOM
- 绑定值
绑定DOM
import {useRef} from "react";
const Demo = () => {
const titleRef = useRef();
const inputRef = useRef();
//ref对象不变,ref的current属性才是dom本身
const showTitleDom = () => {
console.log(titleRef.current)
inputRef.current.focus() //input聚焦
}
return (
<div>
<h3 ref={titleRef}>hello world</h3>
<input type="text" ref={inputRef}/>
<button onClick={showTitleDom}>查看title的domo</button>
</div>
)
}
export default Demo
验证useRef返回的总是同一个对象
import {useRef, useState} from "react";
let obj = null
//验证useRef无论被调用多少次 在组件的整个生命周期都是保持不变的
const Demo = () => {
const [count, setCount] = useState(0);
const nameRef = useRef()
console.log("obj===nameRef:",obj===nameRef)
obj = nameRef
//使用useRef可以解决闭包陷阱
return (
<div>
<h3>hello world</h3>
<button onClick={e=>setCount(count+1)}>+1</button>
</div>
)
}
export default Demo
绑定值解决闭包陷阱的问题
import {useCallback, useRef, useState} from "react";
//验证ref无论被调用多少次 在组件的整个生命周期都是保持不变的
const Demo = () => {
const [count, setCount] = useState(0);
const countRef = useRef()
countRef.current = count
// 通过使用useRef就可以解决闭包陷阱
const increment = useCallback(()=>{
setCount(countRef.current+1)
},[])
return (
<div>
<h3>{count}</h3>
<button onClick={increment}>useRef:+1</button>
<button onClick={e=>setCount(count+1)}>+1</button>
</div>
)
}
export default Demo