reactjs – 如何在React组件上设置组件默认道具

前端之家收集整理的这篇文章主要介绍了reactjs – 如何在React组件上设置组件默认道具前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我使用下面的代码在React组件上设置默认道具,但它不起作用.在render()方法中,我可以看到输出“undefined props”已经打印在浏览器控制台上.如何为组件道具定义默认值?
export default class AddAddressComponent extends Component {

render() {
   let {provinceList,cityList} = this.props
    if(cityList === undefined || provinceList === undefined){
      console.log('undefined props')
    }
    ...
}

AddAddressComponent.contextTypes = {
  router: React.PropTypes.object.is@R_502_103@
}

AddAddressComponent.defaultProps = {
  cityList: [],provinceList: [],}

AddAddressComponent.propTypes = {
  userInfo: React.PropTypes.object,cityList: PropTypes.array.is@R_502_103@,provinceList: PropTypes.array.is@R_502_103@,}
你忘了关闭Class括号.
class AddAddressComponent extends React.Component {
  render() {
    let {provinceList,cityList} = this.props
    if(cityList === undefined || provinceList === undefined){
      console.log('undefined props')
    } else {
      console.log('defined props')
    }

    return (
      <div>rendered</div>
    )
  }
}

AddAddressComponent.contextTypes = {
  router: React.PropTypes.object.is@R_502_103@
};

AddAddressComponent.defaultProps = {
  cityList: [],};

AddAddressComponent.propTypes = {
  userInfo: React.PropTypes.object,cityList: React.PropTypes.array.is@R_502_103@,provinceList: React.PropTypes.array.is@R_502_103@,}

ReactDOM.render(
  <AddAddressComponent />,document.getElementById('app')
)
<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>
<div id="app" />
原文链接:https://www.f2er.com/react/301253.html

猜你在找的React相关文章