How to set component default props on React component

后端 未结 9 884
孤街浪徒
孤街浪徒 2020-12-07 13:52

I use the code below to set default props on a React component but it doesn\'t work. In the render() method, I can see the output \"undefined props\" was printe

相关标签:
9条回答
  • 2020-12-07 14:25
    class Example extends React.Component {
      render() {
        return <h1>{this.props.text}</h1>;
      }
    }
    
    Example.defaultProps = { text: 'yo' }; 
    
    0 讨论(0)
  • 2020-12-07 14:26

    First you need to separate your class from the further extensions ex you cannot extend AddAddressComponent.defaultProps within the class instead move it outside.

    I will also recommend you to read about the Constructor and React's lifecycle: see Component Specs and Lifecycle

    Here is what you want:

    import PropTypes from 'prop-types';
    
    class AddAddressComponent extends React.Component {
      render() {
        let { provinceList, cityList } = this.props;
        if(cityList === undefined || provinceList === undefined){
          console.log('undefined props');
        }
      }
    }
    
    AddAddressComponent.contextTypes = {
      router: PropTypes.object.isRequired
    };
    
    AddAddressComponent.defaultProps = {
      cityList: [],
      provinceList: [],
    };
    
    AddAddressComponent.propTypes = {
      userInfo: PropTypes.object,
      cityList: PropTypes.array.isRequired,
      provinceList: PropTypes.array.isRequired,
    }
    
    export default AddAddressComponent;
    
    0 讨论(0)
  • 2020-12-07 14:28

    If you're using a functional component, you can define defaults in the destructuring assignment, like so:

    export default ({ children, id="menu", side="left", image={menu} }) => {
      ...
    };
    
    0 讨论(0)
提交回复
热议问题