How to set component default props on React component

后端 未结 9 886
孤街浪徒
孤街浪徒 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:21

    use a static defaultProps like:

    export default class AddAddressComponent extends Component {
        static defaultProps = {
            provinceList: [],
            cityList: []
        }
    
    render() {
       let {provinceList,cityList} = this.props
        if(cityList === undefined || provinceList === undefined){
          console.log('undefined props')
        }
        ...
    }
    
    AddAddressComponent.contextTypes = {
      router: React.PropTypes.object.isRequired
    }
    
    AddAddressComponent.defaultProps = {
      cityList: [],
      provinceList: [],
    }
    
    AddAddressComponent.propTypes = {
      userInfo: React.PropTypes.object,
      cityList: PropTypes.array.isRequired,
      provinceList: PropTypes.array.isRequired,
    }
    

    Taken from: https://github.com/facebook/react-native/issues/1772

    If you wish to check the types, see how to use PropTypes in treyhakanson's or Ilan Hasanov's answer, or review the many answers in the above link.

提交回复
热议问题