如何将React.Children.map与React.cloneElement一起使用,并使用flow@0.53.0

时间:2017-08-16 20:21:19

标签: reactjs flowtype

如果我将父组件的子组件键入Node,则表示children是传递给React.Children.map的错误类型。但是,如果我将其键入ChildrenArray<any>,则表示我传递给React.cloneElement的类型不正确。

Scenario 1

import * as React from 'react';

type Props = {
  children?: React.ChildrenArray<any>,
};

class Test extends React.Component<Props> {
  props: Props;

  render() {
    return React.Children.map(this.props.children, child => 
      React.cloneElement(child, {})
    );
  }
}

<Test>
  <span>foo</span>
  <span>bar</span>
</Test>

Scenario 2

import * as React from 'react';

type Props = {
  children?: Node,
};

class Test extends React.Component<Props> {
  props: Props;

  render() {
    return React.Children.map(this.props.children, child => 
      React.cloneElement(child, {})
    );
  }
}

<Test>
  <span>foo</span>
  <span>bar</span>
</Test>

1 个答案:

答案 0 :(得分:2)

第一个例子的问题是使用React.ChildrenArray<any>。实际情况并非如此,因为它们必须是React可以理解为节点的元素。如果我将其更改为React.ChildrenArray<*>let React infer the allowed type,它似乎工作正常。