- useRef
- forwardRef
- useRef
- 用于在一个组件不断 render 保持不变的值
- 初始化: const count = useRef (0)
- 读取: count.current
- useRef 在变化是不会自动 render
function App(){
const count = useRef(0)
const [n,setN] = useState(0)
const [_,set_] = useState(0)
const addN =()=>{
count.current+=1
set_(Math.random())
}
return (
<div>
<div>
ref:{count.current}
<button onClick={addN}>addN</button>
</div>
</div>
)
}
- useRef 的 props 无法传递 ref 属性
- forwarRef 可以实现 ref 的传递
- 两次 ref 传递得到 button 的引用
- 用法
- 可以用来引用 dom 对象
- 也可以用来引用普通对象 基本使用
function App(){
const buttonRef = useRef(null)
return (
<div>
<Button3 ref={buttonRef}>button</Button3>
</div>
)
}
const Button3 = React.forwardRef((props,ref)=>{
return(
<button ref={ref} {...props}></button>
)
})