ReactJs: What should the PropTypes be for this.props.children?

前端 未结 8 1136
梦如初夏
梦如初夏 2020-12-04 05:49

Given a simple component that renders its children:

class ContainerComponent extends Component {
  static propTypes = {
    children: PropTypes.object.isRequ         


        
8条回答
  •  一个人的身影
    2020-12-04 06:32

    Try a custom propTypes :

     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
    
    }
    

    Fiddle

    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 (
          
    {this.props.children}
    ); } } class App extends Component { render(){ return (
    1
    2
    ) } } ReactDOM.render( , document.querySelector('section'))
    
    
    
    

提交回复
热议问题