React.cloneElement Inexact类型与确切类型不兼容

时间:2017-08-30 11:51:25

标签: flowtype

使用React.cloneElement会导致类型错误,我似乎无法解决。

class Dropdown extends React.Component<{ children?: React.ChildrenArray<React.Element<typeof Item>> }> {
     render() {
         React.Children.map(this.props.children, child => 
             React.cloneElement(child)
         );
     }
}

以下类型错误:

91:         React.cloneElement(child, {
                            ^^^^^ read-only array type. Inexact type is incompatible with exact type
            v--------------------------
91:         React.cloneElement(child, {
92:           onClick: () => this.setState({ open: false }),
93:         }),
           -^ exact type: object type

据我所知,这是将React.Children与React.cloneElement结合使用的正确方法。

1 个答案:

答案 0 :(得分:0)

我不确定您使用的是哪个版本的流,我没有<Item>的功能定义,但是当您从子项中删除?时它似乎有效,因此需要数组:

//@flow
import * as React from 'react'

const Item = () => 'hello world'

class Dropdown extends React.Component<{ children: React.ChildrenArray<React.Element<typeof Item>> }> {
     render() {
         React.Children.map(this.props.children, child => 
             React.cloneElement(child)
         );
     }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

SO编辑器似乎不喜欢Flow,所以请尝试“尝试流程”,这里: https://flow.org/try/#0PTACDMBsHsHcCgCWBbADtATgFwAQCocBDAZxwCUBTQgY13A2mRwHIMrbn55roA7Y3AEksFJgF4cACgCUOMQD4WACwqQYOWJkgATTt0glSAEQaptcXjgoAPEb22lKNLADoAwo3S8KvLAB4AbxxqJUQdNl4ALnJ2VzdQ8J8AQQwMQgBPPydaFwBRSFEffyx01ApocBxhUXlFAF9FAPgcFpaI7QoMGRwm1r6W7LiE7QiXZEJUSSxQ4hdUU1mQsJGfABpg4blFZv7dmOcXahhvfMLfSSWdaR296QBuG5a6+DqgA