我正在尝试将React.forwardRef
添加到如下所示的现有组件中:
type Props<T> = {
someProp: T,
}
const Component = <T>({someProp}: Props<T>) => {...}
现在这是组件使用Props<T>
,其中T
是某种通用类型。我在添加React.forwardRef
时遇到了困难,并且在输入时没有错误也没有妥协。
以下是我尝试过的一些事情:
// Complains T doesn't exist
const Component = React.forwardRef<Props<T>, HTMLElement>((props, ref) => {...})
// Multiple errors
type Props<T> = {
value: T,
onChange: T => void,
}
const ChildComponent = <T>() => React.forwardRef<Props<T>, HTMLDivElement>((props, ref) => {
return <div ref={ref}>123</div>;
});
const ParentComponent = () => {
const [value, setValue] = React.useState(123);
const onChange = newValue => setValue(newValue);
return <ChildComponent />;
};
===============================================================================================
All branches are incompatible:
• Either inexact AbstractComponent [1] is incompatible with exact React.Element [2].
• Or AbstractComponent [1] is incompatible with React.Portal [3].
• Or property @@iterator is missing in AbstractComponent [1] but exists in $Iterable [4].
../x.jsx
7│ onChange: T => void,
8│ }
9│
10│ const ChildComponent = <T>() => **React.forwardRef<Props<T>, HTMLDivElement>((props, ref) => {
11│ return <div ref={ref}>123</div>;
12│ })**;
13│
14│ const ParentComponent = () => {
15│ const [value, setValue] = React.useState(123);
/private/tmp/flow/flowlib_1eb3ba5b/react.js
[2] 18│ | React$Element<any>
[3] 19│ | React$Portal
[4] 20│ | Iterable<?React$Node>;
:
[1] 297│ ): React$AbstractComponent<Config, Instance>;
您知道如何在流中将forwardRef与泛型类型一起使用吗?
这样的东西对您有用吗?
import React, { forwardRef } from 'react';
function GenericComponent<T>(props: { someProp: T }) {
return null;
}
const ForwardedRefGenericComponent = forwardRef(
(props, ref) => <GenericComponent ref={ref} {...props} />
);
function App() {
// Examples of using ForwardedRefGenericComponent
return (
<div>
<ForwardedRefGenericComponent someProp={42} />
<ForwardedRefGenericComponent someProp={"abc"} />
<ForwardedRefGenericComponent someProp={true} />
<ForwardedRefGenericComponent someProp={["x", "y"]} />
<ForwardedRefGenericComponent someProp={{ x: "y" }} />
</div>
);
}
Flow应该足够聪明,可以为您推断类型,因此无需为ForwardedRefGenericComponent
显式声明类型。