Parents with one child

For some components, it makes no sense to have more than one child. For these cases, you would use the React.Element type instead of the React.ChildrenArray type:

// @flow
import * as React from 'react';
import Child from './Child';

type Props = {
  children: React.Element<Child>,
};
 
const ParentWithOneChild = ({ children }: Props) => (
  <section>
    <h2>Parent With One Child</h2>
    {children}
  </section>
);
export default ParentWithOneChild;

As with the example before this one, you can still specify the type of child component that is allowed. In this case, the child component is called Child, imported from './Child'. Here's how you would pass this component a child component:

<ParentWithOneChild> 
  <Child /> 
</ParentWithOneChild> 

If you were to pass it multiple Child components, Flow would complain:

    Property `children` is incompatible:
         24:         <ParentWithOneChild>
                     ^^^^^^^^^^^^^^^^^^^^ React children array. Inexact type is incompatible with exact type
          6:   children: React.Element<Child>,
                         ^^^^^^^^^^^^^^^^^^^^ object type. See: src/ParentWithOneChild.js:6
  

Once again, the Flow error message shows you exactly what is wrong with your code and where.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.117.153.38