我有以下组件
type PropTypes<T> = {
items: T[],
header: (item: T) => React.Element<*>,
body: (item: T) => React.Element<*>,
}
type StateTypes<T> = {
expandItem: ?T,
};
export default class Accordian<T> extends React.Component {
props: PropTypes<T>;
state: StateTypes<T>;
setExpandItem: (expandItem: ?T) => void;
constructor(props: PropTypes<T>) {
super(props);
...
}
}
我真的很希望它从 items
推断出 header
的参数具有相同的类型。相反,当我用
<Accordian
items={list}
header={listItem => ...}
/>
我收到:
-^ React element `Accordian`
20: export default class Accordian<T> extends React.Component {
^ T. This type is incompatible with.
See: src/App/components/Accordian/index.js:20
19: banks: GenericBank[],
^^^^^^^^^^^ object type
我找到了 similar question对于 TypeScript,但我想知道是否可以推断 FlowType 中 React 元素的 props 的泛型类型?
最佳答案
您的示例不起作用,因为您正在将 Accordion 的状态初始化为字符串。
class Accordian<T> extends React.Component<PropTypes<T>, StateTypes<T> {
state = {
expandItem: '1'
};
}
string
与类型 T
不兼容,因为 T
可能并不总是 string
。 Accordion 类在使用之前无法知道 T 是什么类型,因此它需要处理所有可能的类型。
如果删除此状态初始值设定项,代码就可以正常工作。如果您想将初始扩展项设置为 items
数组 Prop 中的第一项,您也可以在类构造函数中执行此操作
class Accordian<T> extends React.Component<PropTypes<T>, StateTypes<T>> {
constructor(props) {
super(props)
this.setState({
expandItem: this.props.items[0]
});
}
}
关于reactjs - FlowType - 推断 React 组件的通用类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46577548/