React.js 中的转发 ref
react jsjavascript libraryfront end technology更新于 2025/11/7 1:48:17
将 ref 传递给子组件称为转发 ref。React 提供了一个 createRef 函数来为元素创建 ref。
forwardRef 是一个将 ref 传递给子组件的函数。
示例
// ExampleRef.js
const ExampleTextInput = React.forwardRef((props, ref) => (
<input type="text" placeholder="Welcome" ref={ref} />
));
const exampleInputRef = React.createRef();
class NewTextInput extends React.Component {
handleFormSubmit = e => {
e.preventDefault();
console.log(“Entered value: ”+exampleInputRef.current.value);
};
render() {
return (
<div>
<form onSubmit={e => this.handleFormSubmit(e)}>
<NewTextInput ref={exampleInputRef} />
<button>Submit</button>
</form>
</div>
);
}
}
顾名思义,Ref 转发就是接收 ref 并将其传递给子组件。
ExampleTextInput 中的子组件输入通过 React.forwardRef 函数接收 ref。
创建 forwardref 的步骤
- 使用 React.createRef 创建 ref 并将其赋值给变量元素
- 将上面创建的 ref 作为 jsx 属性附加到组件
- 使用 ref 的组件有一个 forwardref 函数,该函数接受 props 和 ref 作为参数。
- ref 参数传递给子组件
- 子组件将 ref 作为 jsx 属性使用
- 我们将这个 ref 参数向下转发到 <button ref={ref}>通过将其指定为 JSX 属性来实现。
- 附加 ref 后,ref.current 将指向 <button> DOM 节点。
将 forwardRef 与高阶组件结合使用 −
示例
const InputHoc = ProvidedComponent => {
const forwardRef = (props, ref) => {
const onValueInput = () => console.log(“ref value: ”+ref.current.value);
return < ProvidedComponent
forwardedRef={ref}
onChange={onValueInput}
{...props} />;
};
return React.forwardRef(forwardRef);
};
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

