赞
踩
useRef 是一个 React Hook,它能帮助引用一个不需要渲染的值。也就是说useRef可以存储一个值,但是不被组件渲染,仅仅只是引用,主要包括两个方面,例如使用ref引用一个值,使用ref引用一个dom节点,本文将会从计数器,文本框聚焦的案例来进一步说明这useRef的用法
在这个计数器案例中,我们使用了useRef来引用一个变量ref,初始值为0,ref.current代表引用当前ref的值,在点击后获取到当前的值再加1,按道理来说组件应该渲染{ref.current},但是因为useRef的特点,他只在组件初始渲染的时候显示一次,后续便不会参与渲染,仅仅只是作为当前值的引用,通过current属性获取到值,可以从结果图中看到,渲染的值没有变,组件中的ref也没有变
import { useRef } from 'react'; import './App.css'; function App() { const ref = useRef(0); function handleClick() { ref.current = ref.current + 1; alert('You clicked ' + ref.current + ' times!'); } return ( <div className="App"> <button onClick={handleClick}> 点击! </button> <p>{ref.current}</p> </div> ); } export default App;
在这里使用useRef来引用输入框dom节点,初始设置为空,给输入框绑定一个ref属性,点击按钮之后将引用当前的dom进行聚焦,可以看见组件的ref上有输入框的dom,并且点击之后输入框聚焦
import { useRef } from 'react'; import './App.css'; function App() { const inputRef = useRef<HTMLInputElement>(null); const handleClick = () => { if (inputRef.current) { inputRef.current.focus(); } } return ( <div className="App"> <input ref={inputRef} /> <button onClick={handleClick}> 聚焦输入框 </button> </div> ); } export default App;
不要在渲染期间写入或者读取 ref.current。
React 期望组件主体 表现得像一个纯函数:
如果输入的(props、state 与 上下文)都是一样的,那么就应该返回一样的 JSX。
以不同的顺序或用不同的参数调用它,不应该影响其他调用的结果。
在 渲染期间 读取或写入 ref 会破坏这些预期行为。
function MyComponent() {
// ...
// 不要在渲染期间写入 ref
myRef.current = 123;
// ...
// 不要在渲染期间读取 ref
return <h1>{myOtherRef.current}</h1>;
}
可以在 事件处理程序或者 Effect 中读取和写入 ref。
function MyComponent() {
// ...
useEffect(() => {
// 可以在 Effect 中读取和写入 ref
myRef.current = 123;
});
// ...
function handleClick() {
// 可以在事件处理程序中读取和写入 ref
doSomething(myOtherRef.current);
}
// ...
}
如果不得不在渲染期间读取 或者写入,那么应该 使用 state 代替。
这是关于useRef的基础讲解,详细请参考官方文档官方文档
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。