向你的组件暴露 ref
要暴露 ref 最关键的就是 forwardRef
案例:
自定义 React 组件暴露引用 (ref) , 将 inputRef
引用传递给了 MyInput
组件,并且在父组件中通过操作引用来控制子组件内部的行为。
// 向你的组件暴露 ref
import { forwardRef, useRef } from "react";
// 我是子组件
// 暴露了 MyInput 函数
const MyInput = forwardRef((props, ref: any) => {
return <input {...props} ref={ref} />;
});
// 我是父组件
function ExposeRef() {
// 获取到 MyInput 的 ref
const inputRef = useRef<any>(null);
function handleClick() {
// 操作 MyInput 的 ref
inputRef.current.focus();
}
return (
<>
<MyInput ref={inputRef} />
<button onClick={handleClick}>获取焦点</button>
</>
);
}
export default ExposeRef;
定义了一个函数组件 MyInput
,通过使用 forwardRef
包裹组件,以便能够将父组件传递的 ref
属性传递给子组件。forwardRef
函数接受一个回调函数作为参数,该回调函数接收两个参数:props
和 ref
。在这个回调函数中,我们使用 input
元素来展示输入框,并使用展开操作符 ...props
将父组件传递给 MyInput
的其他属性应用到 input
元素上,同时将 ref
设置为传递进来的 ref
。
接着,我们定义了一个名为 ExposeRef
的函数组件。在这个组件内部,我们使用 useRef
创建了一个名为 inputRef
的引用。
在组件的返回值中,我们使用 MyInput
组件,并将 inputRef
作为 ref
属性传递给它。这样,inputRef
就可以在 MyInput
组件内部访问到 input
元素的引用。
同时,我们渲染了一个按钮,并在点击事件的处理函数中操作了 inputRef
的引用。在 handleClick
函数中,我们调用 inputRef.current.focus()
来聚焦到 input
元素上。这样,当用户点击按钮时,输入框会获取焦点。