javascript - 断言 `this.props.children` 中仅传递单个子项

标签 javascript reactjs

有没有办法,使用React.PropTypes来要求this.props.children中只传递一个子元素?

目前,在必须提供单个子项的情况下,我的代码中的内容是在 propTypes 中声明子项是强制的:

propTypes {
    ...
    children: React.PropTypes.element.isRequired
}

…然后断言在 render 方法中传递了正确的数字,例如通过使用:

const singleChild = this.props.children;

...如果超过一个 child 通过,它肯定会吠叫。

我想知道:

  1. 是否有更好、也许更惯用的方式?
  2. 如果还有任何方法要求传递的子元素属于某些特定的元素类型(尽管我猜这违背了 this.props.children 的目的,即允许传递或多或少任意元素)。

最佳答案

根据PropTypes documentation , PropTypes.element.isRequired 是指定组件只有一个子组件的惯用方式。

MyComponent.propTypes = {
  children: PropTypes.element.isRequired
};

另一个选择是使用 React.Children.only()如果只有一个子React元素,它将返回子React元素,否则会出错。如果您需要保证运行时子级的数量,这会很方便,而 propTypes 并不适用于此。

关于问题的第二部分(强制子元素具有特定的元素类型),Airbnb's custom PropType validators包括一个componentWithName。其用法如下:

componentWithName: restrict the prop to only allow a component with a certain name/displayName. Accepts a string, or a regular expression. Also accepts an options object with an optional stripHOCs array of string HOC names to strip off before validating; an HOC name must not contain parentheses and must be in camelCase.

foo: componentWithName('Component')
foo: componentWithName('Component', { stripHOCs: ['withDirection', 'withStyles'] })

关于javascript - 断言 `this.props.children` 中仅传递单个子项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40494691/

相关文章:

Javascript:生成随机漂亮的饱和颜色(选定的调色板)

asp.net - 在 JavaScript 代码中嵌入常量服务器端标签的最佳方法是什么?

reactjs - 如何在 Google Chart 图表(线型)中的 X 轴上添加垂直线?

reactjs - 当容器中的输入值更改时,不会记录 ComponentDidUpdate Inside HOC

javascript - Vanilla JavaScript 向元素添加类

javascript - 如何用 Jest 和测试库/ react 捕获这样的错误

javascript - 如何在 React/React Native 中使用 Emscripten 编译的 JavaScript

reactjs - 如何在 useState Hook 之后立即执行函数?

javascript - 尝试将菜单页面添加到 WordPress 管理站点

javascript - 如何在react.js中包含带有 "new Class({})"init的<script>?