React -高级指引 - Refs转发
admin
2024-03-01 13:48:03

Refs转发

概述

  • 将ref自动地通过组件传递到子组件的技巧
  • 父组件可以通过ref操作子组件,直接使用子组件的DOM

转发 refs 到 DOM 组件

  • 渲染原生 DOM 元素 button 的 FancyButton 组件(子组件)
function FancyButton(props) {return ()
}
  • Ref 转发是一个可选特性,其允许某些组件接收 ref,并将其向下传递给子组件
//子组件
const FancyButton = React.forwardRef((props, ref) => (
))//父组件
//可以直接获取 DOM button 的 ref:
const ref = React.createRef();
ref}>Click me!;//这样,在父组件中可以直接使用DOM button
  • 以下是对上述示例发生情况的逐步解释:
    • 通过调用 React.createRef 创建了一个 React ref 并将其赋值给 ref 变量
    • 指定 ref 为 JSX 属性,将其向下传递给 FancyButton
    • React传递ref给forwardRef作为其第二个参数
    • 向下转发ref参数到button,并将其指定为JSX属性
    • 当ref挂载完成,ref.current将指向button DOM节点

组件库维护者的注意事项

  • 当使用forwardRf时,应将其视为一个新的主版本

在高阶组件中转发 refs

在 DevTools 中显示自定义名称

  • 下面的组件将在DevTools中显示为“ForwardRef”
const WrappedComponent = React.forwardRef((props, ref) => {return ...props} forwardedRef={ref} />;
})
  • 如果命名了渲染函数,DevTools 也将包含其名称(例如 “ForwardRef(myFunction)”)
const WrappedComponent = React.forwardRef(function myFunction(props, ref) {return ...props} forwardedRef={ref} />;}
)
  • 设置函数的 displayName 属性来包含被包裹组件的名称
function logProps(Component) {class LogProps extends React.Component {// ...}function forwardRef(props, ref) {return ...props} forwardedRef={ref} />;}// 在 DevTools 中为该组件提供一个更有用的显示名。// 例如 “ForwardRef(logProps(MyComponent))”const name = Component.displayName || Component.name;forwardRef.displayName = `logProps(${name})`;return React.forwardRef(forwardRef);
}

相关内容

热门资讯

上海旅游节大巡游花车阵容抢先看... 2026上海旅游节大巡游9月12日外滩启幕,21辆全新主题花车携手21支境内外表演方队联袂登场,邀你...
原创 8... 上周门诊来了位 62 岁的张阿姨,得糖尿病快五年了,平时管嘴特别严,糖果、点心、甜饮料一概不碰,连水...
原创 餐... 2026年9月8日晚,南京浦口区泰冯路29号,墨语江南·阿婆菜餐厅户外帐篷里,灯火温润,其间还天降喜...
原创 它... 人到中年肝肾精血慢慢耗损,容易腰膝酸软、头晕眼花、精神疲惫。黄精性平,擅长补肝肾、益精血,搭配不同食...
同样卖奶茶,为何古茗赚了15亿... 出品/联商专栏 撰文/老刀 编辑/蔡建桢 今年上半年,蜜雪、古茗、霸王茶姬、茶百道、沪上阿姨全部盈利...