React.cloneElement Inaccurate type incompatible with exact type

Using React.cloneElement results in a type error that I cannot solve.

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

The following type error:

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

To my knowledge, this is the correct way to use React.Children in combination with React.cloneElement.

+4
source share
1 answer

I'm not sure which version of the stream you are using, and I don't have a function definition for <Item>, but it seems to work when you remove ?from child elements, thereby requiring an array:

//@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>
Run codeHide result

SO, , Flow, "Try Flow" : https://flow.org/try/#0PTACDMBsHsHcCgCWBbADtATgFwAQCocBDAZxwCUBTQgY13A2mRwHIMrbn55roA7Y3AEksFJgF4cACgCUOMQD4WACwqQYOWJkgATTt0glSAEQaptcXjgoAPEb22lKNLADoAwo3S8KvLAB4AbxxqJUQdNl4ALnJ2VzdQ8J8AQQwMQgBPPydaFwBRSFEffyx01ApocBxhUXlFAF9FAPgcFpaI7QoMGRwm1r6W7LiE7QiXZEJUSSxQ4hdUU1mQsJGfABpg4blFZv7dmOcXahhvfMLfSSWdaR296QBuG5a6+DqgA

0

Source: https://habr.com/ru/post/1684742/


All Articles