请注意,使用另一个命名的props (如innerRef
FOR FORWARDING)没有区别,它的工作原理相同.
重构类组件
由于React向函数组件(钩子)移动,您可能希望将类组件代码重构为函数组件without breaking the API.
// Refactor class component API to function component using forwardRef
<Component ref={myRef} />
React.forwardRef
将是您唯一的 Select (详细说明).
清洁空气污染指数
作为一名图书馆作者,你需要一个predictable API,用于ref
次转发.
例如,如果您实现了Component
和someone wants to attach a ref to it,他有两个选项,具体取决于您的API:
<Component innerRef={myRef} />
- 开发者需要知道有一个自定义的转发props
innerRef
号附加在哪个元素上?我们不知道,应该在API中提及还是我们console.log(myRef.current)
<Component ref={myRef} />
- 默认行为类似于HTML元素上使用的
ref
prop,通常附加到内部包装器组件.
请注意,React.forwardRef
can be used用于函数组件和HOC(用于类组件see alternative below).
Ref转发不限于DOM组件.也可以将引用转发到类组件实例.
对于函数组件,forwardRef
有时附带useImperativeHandle
combo(在类组件中,您只需调用ref instance:ref.current.myAttr()
上的类方法).
// Same usage
<Component ref={myRef} />
const Component = React.forwardRef((props, ref) => {
// you can forward ref <div ref={ref} />
// you can add custom attributes to ref instance with `useImperativeHandle`
// like having ref.myAttribute() in addition to ones attached to other component.
});
ref
个props 中的102个没有forwardRef
个.
对于类组件,仅此代码就将ref附加到CLASS INSTANCE,这本身并不有用,需要另一个ref来转发:
// usage, passing a ref instance myRef to class Component
<Component ref={myRef} />
完整示例,请查看日志(log):
// We want to forward ref to inner div
class ClassComponent extends React.Component {
innerRef = React.createRef();
render() {
// Notice that you can't just `this.props.ref.current = node`
// You don't have `ref` prop, it always `undefined`.
return <div ref={this.innerRef}>Hello</div>;
}
}
const Component = () => {
const ref = React.useRef();
useEffect(() => {
// The ref attached to class instance
console.log(ref.current);
// Access inner div through another ref
console.log(ref.current.innerRef);
}, []);
return <ClassComponent ref={ref} />;
};
在函数组件中,它甚至不起作用,因为函数没有实例.
默认情况下,不能对函数组件使用ref属性,因为它们没有实例.[1]