【发布时间】:2017-10-01 08:07:08
【问题描述】:
请看下面的代码。我必须进行两次强制转换以避免任何流量错误。如果我改用注释掉的行,它会抱怨。
/* @flow */
import * as React from "react";
type ConfObj = { label: string };
type Conf = React.Node | ConfObj;
type MyComponentProp = {
confs: Array<Conf>,
}
export default function MyComponent({
confs = [],
}: MyComponentProp) {
const items = confs.map((item, idx) => {
if (React.isValidElement(item)) {
// return React.cloneElement(item, {
return React.cloneElement(((item: any): React.Element<*>), {
key: idx.toString(),
});
}
const item2 = ((item: any): ConfObj);
return <span>{item2.label}</span>;
// return <span>{item.label}</span>;
});
return <div>items</div>
}
有没有更好的方法来避免强制转换。有没有更好的方法来写isValidElement,这样一旦if条件匹配,flow就可以推断出类型。例如,如果它是一个有效的反应元素,我为什么需要强制转换它?或者如果不是,为什么访问label 会出错?
【问题讨论】:
标签: javascript reactjs flowtype