ReactJs: What should the PropTypes be for this.props.children?

前端 未结 8 1105
梦如初夏
梦如初夏 2020-12-04 05:49

Given a simple component that renders its children:

class ContainerComponent extends Component {
  static propTypes = {
    children: PropTypes.object.isRequ         


        
相关标签:
8条回答
  • 2020-12-04 06:55

    For me it depends on the component. If you know what you need it to be populated with then you should try to specify exclusively, or multiple types using:

    PropTypes.oneOfType 
    

    If you want to refer to a React component then you will be looking for

    PropTypes.element
    

    Although,

    PropTypes.node
    

    describes anything that can be rendered - strings, numbers, elements or an array of these things. If this suits you then this is the way.

    With very generic components, who can have many types of children, you can also use the below - though bare in mind that eslint and ts may not be happy with this lack of specificity:

    PropTypes.any
    
    0 讨论(0)
  • 2020-12-04 06:55

    The PropTypes documentation has the following

    // Anything that can be rendered: numbers, strings, elements or an array
    // (or fragment) containing these types.
    optionalNode: PropTypes.node,
    

    So, you can use PropTypes.node to check for objects or arrays of objects

    static propTypes = {
       children: PropTypes.node.isRequired,
    }
    
    0 讨论(0)
提交回复
热议问题