我是新手,我无法成功将它与react-native一起正确使用。我不知道如何加载RN类型。
例如,我正在尝试键入一个将返回nativeEvent.layout
类型的LayoutRectangle
的函数。
我尝试过:import * as RN from 'react-native';
但是按原样使用它会给我Cannot resolve name LayoutRectangle
和RN.LayoutRectangle
给我:Cannot get RN.LayoutRectangle because property LayoutRectangle is missing in module react-native [1]
这是我要制作的示例组件。
// @flow
import * as React from 'react';
import * as RN from 'react-native';
type CompReference = {
getLocation?: () => LayoutRectangle,
}
type Ref<T> = {
current: null | T
}
type Props = {
value: string
}
function CompFunction({value = ''}: Props = {}, ref: CompReference & Ref<HTMLElement> = {}) {
const location: LayoutRectangle = React.useRef(null);
ref.getLocation = () => location.current || { height: 0, width: 0, x: 0, y: 0 };
return (<RN.Text onLayout={({nativeEvent}) => location.current = nativeEvent.layout}>{value}</RN.Text>);
}
const Comp = React.forwardRef<Props, CompReference & Ref<HTMLElement>>(CompFunction);
Comp.displayName = 'Comp';
export default Comp;
我也收到有关forwardRef的错误:
Cannot call `React.forwardRef` with `CompFunction` bound to `render` because property `current` is missing in function type [1] but exists in `Ref` [2] in the second argument. (index.js:34:76)flow
Cannot call `React.forwardRef` with `LetterFunction` bound to `render` because property `getLocation` is missing in object type [1] but exists in `CompReference` [2] in the second argument. (index.js:34:76)flow
Cannot call `React.forwardRef` with `CompFunction` bound to `render` because property `getLocation` is missing in statics of function type [1] but exists in `CompReference` [2] in the second argument. (index.js:34:76)flow
Cannot call `React.forwardRef` with `CompFunction` bound to `render` because property `current` is missing in `HTMLElement` [1] but exists in `Ref` [2] in property `current` of the second argument. (index.js:34:76)flow
Cannot call `React.forwardRef` with `CompFunction` bound to `render` because in property `current` of the second argument: Either `CompReference` [1] is incompatible with `HTMLElement` [2]. Or `Ref` [3] is incompatible with `HTMLElement` [2]. (index.js:34:76)flow
我在做什么错了?
答案 0 :(得分:0)
使用Flow时,您需要导入类型。
所以您需要添加类似的内容
// @flow
import * as React from 'react';
import * as RN from 'react-native';
import type {LayoutRectangle} from 'CoreEventTypes'; //Or wherever your type LayoutRectangle is defined
请注意,在我的版本中,我可能没有nativeEvent.layout
类型的Layout
,并且没有current
属性。 sub>
注意:如果类型未导出到任何地方,则可以使用:
import typeof {LayoutRectangle} from 'react-native';
来源:https://flow.org/en/docs/types/modules/#importing-and-exporting-types-