请注意,使用另一个命名的 prop 没有什么区别,比如innerRef
转发,它的工作原理是一样的。
重构类组件
由于 React 转向函数组件(钩子),您可能希望将类组件代码重构为函数组件不破坏 API.
// Refactor class component API to function component using forwardRef
<Component ref={myRef} />
React.forwardRef
将是您唯一的选择(详细说明)。
干净的API
作为图书馆作者,您may want a 可预测API 用于ref
转发。
例如,如果您实施了Component
and 有人想附加一个参考,根据你的 API,他有两个选项:
<Component innerRef={myRef} />
- 开发人员需要知道有一个用于转发的自定义道具
- 到哪个元素
innerRef
随附的?我们不知道,应该在 API 中提及,否则我们console.log(myRef.current)
<Component ref={myRef} />
- 默认行为类似于
ref
prop 用于 HTML 元素,通常附加到内部包装组件。
请注意React.forwardRef
可以使用对于函数组件和 HOC(对于类组件请参阅下面的替代方案).
引用转发不限于 DOM 组件。您也可以将引用转发到类组件实例。
对于功能组件来说,forwardRef
有时带有useImperativeHandle组合(在类组件中,您只需调用 ref 实例上的类方法: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.
});
重要行为 of ref
支柱无forwardRef
.
对于类组件,仅此代码会将 ref 附加到类实例它本身没有用,需要另一个引用来转发:
// usage, passing a ref instance myRef to class Component
<Component ref={myRef} />
完整示例,检查日志:
// 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]
-
前向引用.
-
Refs 和 DOM.
- 为什么我们需要ref转发?