我有以下这个组件
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); ... } }
我真的很喜欢它从项目推断知道标题的参数具有相同的类型.相反,当我初始化组件时
<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 for TypeScript,但我想知道是否有可能在FlowType中推断React元素的道具上的泛型类型?
解决方法
您的示例不起作用,因为在其中您将手风琴的状态初始化为字符串.
class Accordian<T> extends React.Component<PropTypes<T>,StateTypes<T> { state = { expandItem: '1' }; }
字符串与类型T不兼容,因为T可能并不总是字符串.在使用之前,手风琴类不能知道T是什么类型,所以它需要处理所有可能的类型.
如果删除此状态初始化程序,代码就可以正常工作.如果要将初始扩展项设置为items数组prop中的第一项,则也可以在类构造函数中执行此操作
class Accordian<T> extends React.Component<PropTypes<T>,StateTypes<T>> { constructor(props) { super(props) this.setState({ expandItem: this.props.items[0] }); } }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。