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

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

Given a simple component that renders its children:

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


        
8条回答
  •  -上瘾入骨i
    2020-12-04 06:46

    The answers here don't seem to quite cover checking the children exactly. node and object are too permissive, I wanted to check the exact element. Here is what I ended up using:

    • Use oneOfType([]) to allow for single or array of children
    • Use shape and arrayOf(shape({})) for single and array of children, respectively
    • Use oneOf for the child element itself

    In the end, something like this:

    import PropTypes from 'prop-types'
    import MyComponent from './MyComponent'
    
    children: PropTypes.oneOfType([
      PropTypes.shape({
        type: PropTypes.oneOf([MyComponent]),
      }),
      PropTypes.arrayOf(
        PropTypes.shape({
          type: PropTypes.oneOf([MyComponent]),
        })
      ),
    ]).isRequired
    

    This issue helped me figure this out more clearly: https://github.com/facebook/react/issues/2979

提交回复
热议问题