当前位置:首页 > React

react如何引用传递

2026-02-11 19:16:34React

引用传递的概念

在 React 中,引用传递(Ref Forwarding)是一种将 ref 属性自动传递给子组件的技术。默认情况下,ref 不会像普通 props 那样传递,需要通过 forwardRef 显式实现。

react如何引用传递

基本用法

使用 React.forwardRef 包装子组件,将 ref 作为第二个参数传递:

react如何引用传递

const ChildComponent = React.forwardRef((props, ref) => {
  return <div ref={ref}>{props.children}</div>;
});

// 父组件中使用
function ParentComponent() {
  const childRef = React.useRef();
  return <ChildComponent ref={childRef}>Content</ChildComponent>;
}

类组件中的引用传递

类组件需要通过 forwardRef 包裹,并在子组件内部将 ref 绑定到 DOM 元素或实例:

class ChildClass extends React.Component {
  render() {
    return <div ref={this.props.ref}>Class Component</div>;
  }
}
const ForwardedChild = React.forwardRef((props, ref) => (
  <ChildClass ref={ref} {...props} />
));

高阶组件(HOC)中的引用传递

若子组件被高阶组件包装,需通过 forwardRef 确保 ref 穿透到原始组件:

function withLogging(WrappedComponent) {
  return React.forwardRef((props, ref) => {
    return <WrappedComponent ref={ref} {...props} />;
  });
}

注意事项

  • ref 仅能用于 DOM 元素或类组件实例,函数组件默认无实例。
  • 避免滥用 ref,优先通过 props 和状态管理数据流。
  • 使用 useImperativeHandle 可自定义暴露给父组件的实例方法(函数组件中)。

示例:函数组件暴露方法

const Child = React.forwardRef((props, ref) => {
  const inputRef = useRef();
  useImperativeHandle(ref, () => ({
    focus: () => inputRef.current.focus()
  }));
  return <input ref={inputRef} />;
});

标签: react
分享给朋友:

相关文章

如何开发react

如何开发react

开发React应用的基本步骤 安装Node.js和npm 确保系统中已安装Node.js(包含npm)。可通过官网下载安装包,安装后验证版本: node -v npm -v 创建React项目…

react如何安装

react如何安装

安装React的步骤 确保已安装Node.js(建议版本12或更高),可通过以下命令检查版本: node -v npm -v 使用Create React App快速搭建项目(推荐): npx c…

react 如何debug

react 如何debug

React 调试方法 使用 React Developer Tools React Developer Tools 是浏览器扩展,支持 Chrome 和 Firefox。安装后,可以在开发者工具中查看…

react如何清理

react如何清理

清理 React 项目的方法 清理未使用的依赖项 运行 npm prune 或 yarn install --production 可以移除 node_modules 中未在 package.json…

webstorm如何运行react

webstorm如何运行react

运行 React 项目的方法 在 WebStorm 中运行 React 项目需要确保项目已正确配置,并且依赖项已安装。以下是具体操作步骤: 确保项目依赖已安装 打开终端(Terminal),导航到项…

react如何代码优化

react如何代码优化

减少不必要的重新渲染 使用 React.memo 包装函数组件以避免在 props 未变化时重新渲染。对于类组件,可以通过 shouldComponentUpdate 或继承 PureComponen…