Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

React 获取 children ref #54

Open
jtwang7 opened this issue Aug 13, 2022 · 0 comments
Open

React 获取 children ref #54

jtwang7 opened this issue Aug 13, 2022 · 0 comments
Labels

Comments

@jtwang7
Copy link
Owner

jtwang7 commented Aug 13, 2022

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 将覆盖之前的。

@jtwang7 jtwang7 added the React label Aug 13, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant