React函数式组件使用Ref
<p>目录:</p><ol>
<li>简介</li>
<li>useRef</li>
<li>forwardRef</li>
<li>useImperativeHandle</li>
<li>回调Ref</li>
</ol>
<h3 id="简介">简介</h3>
<p>大家都知道React中的<code>ref</code>属性可以帮助我们获取子组件的实例或者Dom对象,进而对子组件进行修改,是一个很方便的特性。在传统类组件中,我们通过使用 <code>React.createRef()</code> 创建的,并通过 <code>ref </code>属性附加到 <code>React 元素</code>来使用。而随着hooks的越来越广泛的使用,我们有必要了解一下在函数式组件中,如何使用Ref.<br>
想要在函数式组件中使用Ref,我们必须先了解两个Api,<code>useRef</code>和<code>forwardRef</code></p>
<h3 id="useref">useRef</h3>
<pre><code>const refContainer = useRef(initialValue);
</code></pre>
<p>useRef返回一个可变的ref对象,其<code>.current</code>属性被初始化为传入的参数<code>(initialValue)</code>。返回的ref对象在整个生命周期内保持不变。<br>
下面看一个例子</p>
<pre><code>function TextInputWithFocusButton() {
// 关键代码
const inputEl = useRef(null);
const onButtonClick = () => {
// 关键代码,`current` 指向已挂载到 DOM 上的文本输入元素
inputEl.current.focus();
};
return (
<>
// 关键代码
<input ref={inputEl} type="text" />
<button onClick={onButtonClick}>Focus the input</button>
</>
);
}
</code></pre>
<p>效果如下<br>
<img src="https://upload-images.jianshu.io/upload_images/11219832-56e61279beb2bbfd.gif?imageMogr2/auto-orient/strip"></p>
<p>可以看到我们点击button,先通过<code>useRef</code>创建一个ref对象<code>inputEl</code>,然后再将<code>inputEl</code>赋值给<code>input</code>的<code>ref</code>,最后,通过<code>inputEl.current.focus()</code>就可以让input聚焦。<br>
然后,我们再想下,如果input不是个普通的dom元素,而是个组件,该怎么办呢?<br>
这就牵扯到另外一个api,<code>forwardRef </code>。</p>
<h3 id="forwardref">forwardRef</h3>
<p>我们修改一下上面的例子,将input单独封装成一个组件<code>TextInput</code>。</p>
<pre><code>const TextInput =forwardRef((props,ref) => {
return <input ref={ref}></input>
})
</code></pre>
<p>然后用<code>TextInputWithFocusButton</code>调用它</p>
<pre><code>function TextInputWithFocusButton() {
// 关键代码
const inputEl = useRef(null);
const onButtonClick = () => {
// 关键代码,`current` 指向已挂载到 DOM 上的文本输入元素
inputEl.current.focus();
};
return (
<>
// 关键代码
<TextInput ref={inputEl}></TextInput>
<button onClick={onButtonClick}>Focus the input</button>
</>
);
}
</code></pre>
<p>可以看到React.forwardRef 接受一个渲染函数,其接收 props 和 ref 参数并返回一个 React 节点。<br>
这样我们就将父组件中创建的<code>ref</code>转发进子组件,并赋值给子组件的input元素,进而可以调用它的focus方法。<br>
至此为止,通过useRef+forwardRef,我们就可以在函数式组件中使用ref了。当然,这篇文章还远不止如此,下面还要介绍两个重要的知识点<code>useImperativeHandle</code>和<code>回调Ref</code>,结合上面两个api,让你的代码更加完美。</p>
<h3 id="useimperativehandle">useImperativeHandle</h3>
<p>有时候,我们可能不想将整个子组件暴露给父组件,而只是暴露出父组件需要的值或者方法,这样可以让代码更加明确。而<code>useImperativeHandle</code>Api就是帮助我们做这件事的。<br>
语法:</p>
<pre><code>useImperativeHandle(ref, createHandle, )
</code></pre>
<p><code>useImperativeHandle</code> 可以让你在使用 ref 时自定义暴露给父组件的实例值。<br>
一个例子🌰:</p>
<pre><code>const TextInput =forwardRef((props,ref) => {
const inputRef = useRef();
// 关键代码
useImperativeHandle(ref, () => ({
focus: () => {
inputRef.current.focus();
}
}));
return <input ref={inputRef} />
})
function TextInputWithFocusButton() {
// 关键代码
const inputEl = useRef(null);
const onButtonClick = () => {
// 关键代码,`current` 指向已挂载到 DOM 上的文本输入元素
inputEl.current.focus();
};
return (
<>
// 关键代码
<TextInput ref={inputEl}></TextInput>
<button onClick={onButtonClick}>Focus the input</button>
</>
);
}
</code></pre>
<p>这样,我们也可以使用current.focus()来事input聚焦。这里要注意的是,子组件TextInput中的useRef对象,只是用来获取input元素的,大家不要和父组件的useRef混淆了。</p>
<h3 id="回调ref">回调Ref</h3>
<p>什么是<code>回调Ref</code>呢?<br>
上面的例子,都有一个问题,就是当 <code>ref </code>对象内容发生变化时,<code>useRef</code> 并不会通知你。变更 <code>.current </code>属性不会引发组件重新渲染,看下面这个例子。<br>
比如下面这个例子:</p>
<pre><code>function TextInputWithFocusButton() {
const inputEl = useRef(null);
const = useState("");
useEffect(() => {
setValue(inputEl.current.value);
}, );
const onButtonClick = () => {
// `current` 指向已挂载到 DOM 上的文本输入元素
console.log("input值", inputEl.current.value);
setValue(inputEl.current.value);
};
return (
<>
<div>
子组件: <TextInput ref={inputEl}></TextInput>
</div>
<div>
父组件: <input type="text" value={value} onChange={() => {}} />
</div>
<button onClick={onButtonClick}>获得值</button>
</>
);
}
const TextInput = forwardRef((props, ref) => {
const = useState("");
const inputRef = useRef();
useImperativeHandle(ref, () => ({
value: inputRef.current.value,
}));
const changeValue = e => {
setValue(e.target.value);
};
return <input ref={inputRef} value={value} onChange={changeValue}></input>;
});
</code></pre>
<p><img src="https://upload-images.jianshu.io/upload_images/11219832-38fd1c1c55f494ce.gif?imageMogr2/auto-orient/strip"></p>
<p>可以看到,父组件获取不到子组件实时的值,必须点击按钮才能获取到,即使我写了<code>useEffect</code>,希望它在<code>inputEl</code>改变的时候,重新设置<code>value</code>的值。<br>
那怎么办呢?这就需要回调Ref,我们改一下代码</p>
<pre><code>function TextInputWithFocusButton() {
const = useState("");
const inputEl = useCallback(node => {
if (node !== null) {
console.log("TCL: TextInputWithFocusButton -> node.value", node.value)
setValue(node.value);
}
}, []);
const onButtonClick = () => {
// `current` 指向已挂载到 DOM 上的文本输入元素
console.log("input值", inputEl.current.value);
setValue(inputEl.current.value);
};
return (
<>
<div>
子组件: <TextInput ref={inputEl}></TextInput>
</div>
<div>
父组件: <input type="text" value={value} onChange={() => {}} />
</div>
</>
);
}
const TextInput =forwardRef((props,ref) => {
const = useState('')
const inputRef = useRef();
useImperativeHandle(ref, () => ({
value: inputRef.current.value
}));
const changeValue = (e) =>{
setValue(e.target.value);
}
return <input ref={inputRef} value={value} onChange={changeValue}></input>
})
</code></pre>
<p><img src="https://upload-images.jianshu.io/upload_images/11219832-cf6dc2ae85b0c7db.gif?imageMogr2/auto-orient/strip"></p>
<p>可以看到,这里我们输入时,父组件就可以实时地拿到值了。<br>
这里比较关键的代码就是使用<code>useCallback</code>代替了<code>useRef</code>,<code>callback ref</code>会将当前ref的值变化通知我们。</p>
<p>好,以上就是整理的关于函数式组件中使用Ref的方法。<br>
当然,其中关于api介绍的比较简陋,大家看完可能不知所云。因为此篇文章的主要目的,仅是将散落在官网中关于ref的相关方法进行一下整合,形成一个使用ref的思路,关于api的更深入的了解,还请移步React官网。<br>
如有不足,欢迎指出。</p>
<p>参考文献:<br>
官网中useRef useImperativeHandleApi的介绍<br>
官网中forwardRef的介绍<br>
官网中回调Ref的介绍</p><br><br>
来源:https://www.cnblogs.com/yky-iris/p/12355243.html
頁:
[1]