流类型React ref回调和createRef [英] flow type React ref callback and 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屋!