forwardRef
-
ref 的作用是获取实例,但由于函数组件不存在实例,因此无法通过 ref 获取函数组件的实例引用。而
React.forwardRef就是用来解决这个问题的。 -
React.forwardRef会创建一个 React 组件,这个组件能够将其接收到的 ref 属性转发到自己的组件树。
基本用法
const childRef = useRef(null)
return <Child ref={inputRef} />
- 子组件
// 被包装的函数式组件,第一个参数是 props,第二个参数是转发过来的 ref
import { forwardRef } from 'react';
const MyInput = forwardRef(function MyInput(props, ref) {
const { label, ...otherProps } = props;
return (
<label>
{label}
<input {...otherProps} ref={ref} />
</label>
);
});
参数
props:父组件传递过来的 props。ref:父组件传递的ref属性。ref可以是一个对象或函数。如果父组件没有传递一个 ref,那么它将会是null。你应该将接收到的ref转发给另一个组件,或者将其传递给useImperativeHandle。
返回值
forwardRef返回一个可以在 JSX 中渲染的 React 组件。与作为纯函数定义的 React 组件不同,forwardRef返回的组件还能够接收ref属性。- 父组件
// 父组件
function Form() {
const ref = useRef(null);
function handleClick() {
ref.current.focus();
}
return (
<form>
<MyInput label="Enter your name:" ref={ref} />
<button type="button" onClick={handleClick}>编辑</button>
</form>
);
}