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

问题描述 投票:0回答:9

给定一个渲染其子组件的简单组件:

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

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

export default ContainerComponent;

问题:children prop 的 propType 应该是什么?

当我将其设置为对象时,当我使用具有多个子组件的组件时,它会失败:

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

警告:失败的道具类型:

children
类型的道具
array
无效 供应给
ContainerComponent
,预计
object

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

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

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

请告知,我是否应该不费心去检查儿童元素?

    

reactjs jsx react-proptypes
9个回答
558
投票
propTypes

oneOfType
 尝试类似的操作

PropTypes.node

import PropTypes from 'prop-types' ... static propTypes = { children: PropTypes.oneOfType([ PropTypes.arrayOf(PropTypes.node), PropTypes.node ]).isRequired }



64
投票

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

如果您想引用 React 组件,那么您将寻找

PropTypes.oneOfType

虽然,

PropTypes.element

描述任何可以渲染的东西——字符串、数字、元素或这些东西的数组。如果这适合您,那么这就是方法。

使用

very

通用组件,可以有多种类型的子组件,您还可以使用以下组件。不过我不会推荐它。正如下面的评论中提到的,它确实在某种程度上违背了使用 PropTypes.node 的目的,并且通常还有其他方法来指定组件的需求。另请记住,eslint 和 ts 可能(可能)对这种缺乏特异性不满意:

PropTypes



37
投票
PropTypes 文档

有以下内容 PropTypes.any

因此,您可以使用 
// Anything that can be rendered: numbers, strings, elements or an array // (or fragment) containing these types. optionalNode: PropTypes.node,

来检查对象或对象数组

PropTypes.node



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

node
太宽松了,我想检查确切的元素。这是我最终使用的:

使用
    object
  • 允许单个或一组子元素
    分别对单个子项和一组子项使用 
  • oneOfType([])
  • shape
    使用 
  • arrayOf(shape({}))
  • 作为子元素本身
    
    
    
  • 最后,是这样的:

oneOf

这个问题帮助我更清楚地弄清楚了这一点:
https://github.com/facebook/react/issues/2979


6
投票

import PropTypes from 'prop-types' import MyComponent from './MyComponent' children: PropTypes.oneOfType([ PropTypes.shape({ type: PropTypes.oneOf([MyComponent]), }), PropTypes.arrayOf( PropTypes.shape({ type: PropTypes.oneOf([MyComponent]), }) ), ]).isRequired

如果您想精确匹配某些组件类型,请选中此

MenuPrimary.propTypes = { children: PropTypes.oneOfType([ PropTypes.arrayOf(MenuPrimaryItem), PropTypes.objectOf(MenuPrimaryItem) ]) }



6
投票

const HeaderTypes = [ PropTypes.objectOf(MenuPrimary), PropTypes.objectOf(UserInfo) ] Header.propTypes = { children: PropTypes.oneOfType([ PropTypes.arrayOf(PropTypes.oneOfType([...HeaderTypes])), ...HeaderTypes ]) }



3
投票

children: PropTypes.oneOfType([ PropTypes.arrayOf(PropTypes.node), PropTypes.node, PropTypes.func ])

小提琴

const childrenPropTypeLogic = (props, propName, componentName) => { const prop = props[propName]; return React.Children .toArray(prop) .find(child => child.type !== 'div') && new Error(`${componentName} only accepts "div" elements`); }; static propTypes = { children : childrenPropTypeLogic }
const {Component, PropTypes} = React;

 const  childrenPropTypeLogic = (props, propName, componentName) => {
             var error;
          var prop = props[propName];
    
          React.Children.forEach(prop, function (child) {
            if (child.type !== 'div') {
              error = new Error(
                '`' + componentName + '` only accepts children of type `div`.'
              );
            }
          });
    
          return error;
    };
    
  

class ContainerComponent extends Component {
  static propTypes = {
    children: childrenPropTypeLogic,
  }

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



class App extends Component {
   render(){
    return (
    <ContainerComponent>
        <div>1</div>
        <div>2</div>
      </ContainerComponent>
    )
   }
}

ReactDOM.render(<App /> , document.querySelector('section'))


1
投票
propTypes文档

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> <section />用于React元素,children就是其中之一:

element

然后你可以将它与
// A React element. optionalElement: PropTypes.element,

结合起来
Component.propTypes = { 子级:PropTypes.arrayOf(PropTypes.element).isRequired, };

那么至少需要一个

arrayOf

    


0
投票

children

图片:如果预期类型不同,则在控制台中显示错误

Picture: Shows you error in console if the expected type is different

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.