给定一个简单的组件来呈现其子对象:

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

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

export default ContainerComponent;

Question: What should the propType of the children prop be?

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

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

警告:失败的props 类型:array类型的props children无效

如果我将其设置为数组,如果我只给它一个子元素,它将失败,即:

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

警告:失败的props 类型:无效的props 子对象类型

请告诉我,我是否应该省心做一个关于 children 元素的propTypes判断?

推荐答案

试试这样的oneOfTypePropTypes.node

imp或t PropTypes from 'prop-types'

...

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

static propTypes = {
    children: PropTypes.node.isRequired,
}

Reactjs相关问答推荐

如何将google地址lat收件箱设置为输入值?

react-hook-form问题:为什么getValues不返回大多数当前值?

删除表2的收件箱未按预期工作

无法使用Apollo客户端GraphQL设置Next.js 14

react 路由导航不工作,但手动路由工作

是否将样式应用于父悬停(框架运动)上的子元素?

在Reaction中导入';图片&文件夹时出错

在每页上应用字体-NextJS

在react 中从外部 api 渲染列表

react - 警告:列表中的每个子元素都应该有一个独特的 keys props ,即使我已经设置了 keys

在 React 中将路径与查询变量匹配

使用输入类型文本对 useState 和日期做出react

谁能根据经验提供有关 useEffect 挂钩的更多信息

如何使用 UseState 正确测试组件

使用 yarn 编译 protobuf js 时出现错误pbjs: command not found

react-query、react-hook-form 和表单验证

如何跨微前端 React 应用管理状态管理?

在 Redux 中更新布尔状态时出错

错误未捕获的错误:[App] 不是 组件. 的所有子组件必须是

React中`onScroll`和`onScrollCapture`之间的区别?