有没有办法,使用React.PropTypes
来要求this.props.children
中只传递一个子元素?
目前,在必须提供单个子项的情况下,我的代码中的内容是在 propTypes
中声明子项是强制的:
propTypes {
...
children: React.PropTypes.element.isRequired
}
…然后断言在 render
方法中传递了正确的数字,例如通过使用:
const singleChild = this.props.children;
...如果超过一个 child 通过,它肯定会吠叫。
我想知道:
- 是否有更好、也许更惯用的方式?
- 如果还有任何方法要求传递的子元素属于某些特定的元素类型(尽管我猜这违背了
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/