jtwang7 / React-Note

React 学习笔记
8 stars 2 forks source link

React 获取 children ref #54

Open jtwang7 opened 2 years ago

jtwang7 commented 2 years ago

React 获取 children ref

参考:

代码实现

// 获取 children 的 ref 实例

// 存储目标实例的 ref 容器
const targetRef = useRef<any>(null!);

// 判断 children 是否单元素
const child = React.Children.only(children) as any; 

// 此处配置回调 ref 来获取 ref 对象
const childWithRef = React.cloneElement(child, {
  ref: (ref: any) => {
    targetRef.current = ref;
  },
});

React.cloneElement()

React.cloneElement(
  element,
  [config],
  [...children]
)

React.cloneElement() 几乎等同于:

<element.type {...element.props} {...props}>{children}</element.type>

以 element 元素为样板克隆并返回新的 React 元素。config 中应包含新的 props,key 或 ref。返回元素的 props 是将新的 props 与原始元素的 props 浅层合并后的结果。新的子元素将取代现有的子元素,如果在 config 中未出现 key 或 ref,那么原始元素的 key 和 ref 将被保留。这意味着当通过 ref 获取子节点时,你将不会意外地从你祖先节点上窃取它。相同的 ref 将添加到克隆后的新元素中。如果存在新的 ref 或 key 将覆盖之前的。