流类型React ref回调和createRef [英] flow type React ref callback and createRef

查看:113
本文介绍了流类型React ref回调和createRef的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class Component extends React.Component<ComponentProps> {
  // ...magic
  elementRef = React.createRef();

  render() {
    return this.props.children(this.elementRef);
  }
}

这是我拥有的组件.它基本上将ref回调传递给子级. 然后像这样

This is a component I have. Its basically passing the ref callback to children. and then its used like this

<Component>
  {elementRef => (
    <div ref={elementRef} />
  )}
</Component>

我的Component的意图是孩子们可以将elementRef附加到任何元素上.

The intention of my Component is that the children can attach the elementRef to any element.

但是我在正确键入组件方面遇到很多麻烦.

But I having a lot of trouble type my component correctly.

我现在正在做什么:

type ComponentProps = {
  +children: (
    ref: { current: HTMLDivElement | null } | ((ref: ?HTMLDivElement) => void)
  ) => React.Node,
};

但显然,这仅适用于div.如果我要在span上使用elementRef.流会抱怨.

But obviously this only works for div. If I were to use the elementRef on a span. Flow would complain.

那么我应该如何正确输入Component以便它适用于任何HTML元素?

So how should I type my Component correctly so that it works for any HTML element?

推荐答案

我认为可能会解决您的问题.尚未在文档中.

I think this might solve your problem. It's not yet in the docs.

{current: null | React$ElementRef<ElementType>}

这篇关于流类型React ref回调和createRef的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆