useRef
Refs (opens in a new tab)
ref
引用的缩写 意在 引用一个东西。
在 React
中 ref 是一个
在 React
中几个版本的迭代,从可以直接使用字符串 (opens in a new tab),到 class
组件模式的 createRef
(opens in a new tab),再到 函数式组件的hook
模式 useRef
(opens in a new tab),经历了几次升级。
const refContainer = useRef(initialValue);
useRef
返回一个可变的 ref
对象,this.current
属性被初始化为传递的参数 (initialValue
)。返回的对象将在组件的整个生命周期内持续存在。
function TextInputWithFocusButton() {
const inputEl = useRef(null);
const onButtonClick = () => {
// `current` points to the mounted text input element
inputEl.current.focus();
};
return (
<>
<input ref={inputEl} type="text" />
<button onClick={onButtonClick}>Focus the input</button>
</>
);
}
Last updated on December 16, 2022