小编典典

ReactJs:这个.props.children的PropType应该是什么?

reactjs

给定一个呈现其子级的简单组件:

class ContainerComponent extends Component {
  static propTypes = {
    children: PropTypes.object.isRequired,
  }

  render() {
    return (
      <div>
        {this.props.children}
      </div>
    );
  }
}

export default ContainerComponent;

问题:孩子道具的propType应该是什么?

当我将其设置为对象时,当我将组件与多个子级一起使用时,它将失败:

<ContainerComponent>
  <div>1</div>
  <div>2</div>
</ContainerComponent>

警告:无法道具类型:无效的支柱children型的array 供给ContainerComponent,预计object

如果将其设置为数组,则如果我仅给其一个孩子,则它将失败,即:

<ContainerComponent>
  <div>1</div>
</ContainerComponent>

警告:prop类型失败:提供给ContainerComponent的对象类型无效的prop子代,预期数组。

请告知,我是否不应该为子元素做propTypes检查?


阅读 284

收藏
2020-07-22

共1个答案

小编典典

尝试使用oneOfType或类似的方式PropTypes.node

import PropTypes from 'prop-types'

...

static propTypes = {
    children: PropTypes.oneOfType([
        PropTypes.arrayOf(PropTypes.node),
        PropTypes.node
    ]).isRequired
}

要么

static propTypes = {
    children: PropTypes.node.isRequired,
}
2020-07-22