【问题标题】:How to use React.Children.map with React.cloneElement with flow@0.53.0如何将 React.Children.map 与 React.cloneElement 与 flow@0.53.0 一起使用
【发布时间】:2017-08-22 23:51:21
【问题描述】:

如果我将父组件的子组件键入为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>

【问题讨论】:

标签: reactjs flowtype


【解决方案1】:

第一个例子的问题是React.ChildrenArray&lt;any&gt;的使用。并不是真的可以在那里使用任何东西,因为它们必须是 React 可以理解为节点的元素。如果我将其更改为 React.ChildrenArray&lt;*&gt;let React infer the allowed type,它似乎工作正常。

【讨论】:

    猜你喜欢
    • 2018-10-09
    • 2020-12-22
    • 2018-05-27
    • 2012-08-13
    • 2020-01-08
    • 2017-08-29
    • 1970-01-01
    • 2015-11-18
    • 1970-01-01
    相关资源
    最近更新 更多