【问题标题】:How to restrict the number of child in a component to only one in react native?react-native - 如何将组件中的子级数量限制为只有一个?
【发布时间】:2018-11-02 11:11:33
【问题描述】:

我有一个接受孩子的组件,我想做的是将孩子的数量限制为只有一个,我希望孩子成为反应原生的单个视图或单个文本

【问题讨论】:

  • 如果您能提供更多相关信息,我们将不胜感激,对于初学者,您可以添加您迄今为止尝试过的代码。
  • 我还没试过。

标签: react-native


【解决方案1】:

您可以使用React.Children API,特别是React.Children.only

我认为正确的语法是:

class MyComponent extends React.Component {
  render(){
    return React.Children.only(this.props.children)()
  }
}

这将验证只有一个孩子,并返回那个孩子,如果有多个孩子则抛出错误。

你也可以使用PropTypes

class MyComponent extends React.Component {
  render(){
    const children = this.props.children
    return (
      <>
        {children}
      </>
    )
  }
}

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

如果您想进一步强制您的孩子只是TextView 实例,您可以编写自定义PropTypes validator,这里是example on StackOverflow

【讨论】:

  • 感谢您的支持,我使用的 proptype 菜单对我来说很好 :)
猜你喜欢
  • 2011-10-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-03
  • 1970-01-01
  • 2021-08-15
  • 2021-10-18
  • 2019-02-06
相关资源
最近更新 更多