繁体   English   中英

React props.children的流类型(联合元素|数组)

[英]Flow type for React props.children (union Element | Array)

我有一个容器组件,它是带有children属性的props类型:

type Props = {
    children: Array<React.Element<any>> | React.Element<any>,
    settings: string | Object
};

容器只能包含一个或多个React.Element,并取决于它应该选择正确的操作。

在render函数中,我有类似的东西:

const children = this.props.children;

if ( _.isArray(children) ) {
    return _.map(children, (child, key) => checkListComponent(child, key));
}

else if ( _.isObject(children) ) {
    return checkListComponent(children);
}

主要功能是:

const checkListComponent = (child: React.Element<any>, key) => {
        return child.props.list
            ? React.cloneElement(child, key ? { options, key } : { options })
            : child;
    };

毕竟我在其他情况下遇到Flow错误

return checkListComponent(children);

流:数组类型。 此类型与React $ Element的预期参数类型不兼容。

对于子项道具,似乎忽略了非数组的可能类型。 在Github上发现有关联合数组和对象类型的问题,但是没有任何问题。

有什么解决办法吗?

UPD:

我在props.settings中遇到相同的问题,它可以是从服务器获取设置对象的API URL或直接设置对象。 当我调用axios.get(settings)时(显然现在检查props.settings是一个字符串之前),Flow忽略可能的字符串类型,并抱怨给出的是Object而不是string。 但是当我检查对象类型的设置并设置容器状态时,在下一行

this.setState({ settings: this.props.settings });

它抱怨说String是给定的,而不是Object

怎么可能,我该怎么办? 我可以但不想拥有两个用于设置API和对象的道具。 对于问题的props.children部分来说,这绝对是不可能的。

Flow无法知道_.isArray返回true表示children是一个数组,对_.isObject 您的代码应以

const children = this.props.children;

if (Array.isArray(children) ) {
  return children.map((child, key) => checkListComponent(child, key));
} else {
  return checkListComponent(children);
}

因为Array.isArray是标准的,并且Flow可以知道else块中的children必须是联合中的非数组类型。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM