Ref 是什么
Ref 是 Reference 的缩写,就是引用的意思
与 state 不同的是,ref 不是每次 render 一个版本,它类似于一个全局变量
- 每次渲染 ref 返回值都不变
- ref 变化不会造成 re-render
ref 发生变化应该作为 Side Effect(因为它会影响下次渲染),所以不应该在 render 阶段更新 current 属性。
Ref 的目的
- 访问 DOM 元素
- 作为一个变量
Ref 的使用
class 组件使用 createRef 创建 Ref 实例:
class AutoFocusTextInput extends React.Component {
constructor(props) {
super(props);
this.textInput = React.createRef();
}
componentDidMount() {
this.textInput.current.focusTextInput();
}
render() {
return <CustomTextInput ref={this.textInput} />;
}
}
function 组件使用 useRef HOOK 声明 Ref:
function CustomTextInput(props) {
const textInput = useRef(null);
function handleClick() {
textInput.current.focus();
}
return (
<div>
<input type='text' ref={textInput} />
<input type='button' value='Focus the text input' onClick={handleClick} />
</div>
);
}
Ref 与 render
ref.current 发生变化不会造成 re-render
不应该在 render 阶段更新 ref.current 属性,ref.current 发生变化应该作为 Side Effect(影响下次渲染)
但是异步渲染的时候是可以的(更新 ref.current 属性)
Ref.current 不可作为 hooks 依赖项
Reactjs 并不会跟踪 ref.current 的变化,不要把 ref.current 作为其他 hooks(useMemo, useCallback, useEffect)依赖项
至于 Ref 本身,Ref 是不变的,更不能作为依赖项