React Component children typecheck with typescript

后端 未结 2 1571
终归单人心
终归单人心 2021-01-12 08:29

Here is the scenario:

I have a custom component:

class MyComponent extends React.Component {
  render () {
    return (
      
         


        
2条回答
  •  余生分开走
    2021-01-12 09:21

    I would probably declare SuperPropsType.children as:

    children: React.ReactElement | React.ReactElement[];
    

    To account for the possibility of having both a single and multiple children.

    In any case, as pointed out already, that won't work as expected.

    What you could do instead is declare a prop, let's say subComponentProps: SubPropsType1[], to pass down the props you need to create those SubComponent1s, rather than their JSX, and render them inside SuperComponent:

    interface SuperPropsType {
      children?: never;
      subComponentProps?: SubPropsType1[];
    }
    
    ...
    
    const SuperComponent: React.FC = ({ subComponentProps }) => {
      return (
        ...
    
        { subComponentProps.map(props => ) }
    
        ...
      );
    };
    

提交回复
热议问题