【问题标题】:Flow type for React props.children (union Element | Array)React props.children 的流类型(联合元素 | 数组)
【发布时间】:2018-01-01 18:31:36
【问题描述】:

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

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

Container 可以包含唯一一个或多个 React.Element,这取决于它应该选择正确的操作。

在渲染函数中我有类似的东西:

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;
    };

毕竟我在 else if

中遇到了 Flow 错误
return checkListComponent(children);

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

它似乎忽略了 children 道具可能的非数组类型。我找到了issue on Github 关于联合数组和对象类型,但什么都没有。

这种情况有什么解决办法吗?

UPD:

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

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

它抱怨给出的是 String 而不是 Object

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

【问题讨论】:

    标签: reactjs flowtype flow-typed


    【解决方案1】:

    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 必须是联合中的非数组类型。

    【讨论】:

    • 谢谢,这行得通。但是还有一个问题,显然 Flow 无法了解 lodash 函数,但我已经为 lodash (4.xx) 进行了流类型化,并且有一个声明 isString(value: string): true; isString(value: number|bool|Function|void|null|Object|Array&lt;any&gt;): false; 这是一个字符串以及对象和数组只有any 但正如我在UPD 中所说,用lodash 检查字符串也不起作用。为什么?本机检查与 Flow 配合得很好,但我想为自己弄清楚 Flow 如何处理声明等。
    • 通常在检查某物的类型时,您会希望坚持使用核心语言内容,例如typeof。我不知道 Flow 是否足够聪明来解释那个 Flow 声明。 They are in the process of experimenting with syntax 让图书馆做那种事情,但我认为这还不是官方的。
    猜你喜欢
    • 2017-11-29
    • 1970-01-01
    • 2017-01-21
    • 1970-01-01
    • 2015-12-16
    • 2018-04-15
    • 2015-09-19
    • 1970-01-01
    • 2021-10-21
    相关资源
    最近更新 更多