在react中可以定义默认props,使用es5时,可以使用getDefaultProps:

var MyDemo = React.createClass({
  getDefaultProps: function() {
    return {
      name: 'demo'
    };
  },
  render: function() {
    return <h1>This is my {this.props.name}</h1>;
  }
});

ReactDOM.render(
  <MyDemo />,
  document.getElementById('demo')
);

es6中使用static defaultProps(报错,需要使用static的解决方案见下面):

class MyDemo extends React.Component{
  constructor(props){
    super(props);
  }
//如果babel设置为es6的转码方式,会报错,因为定义静态属性不属于es6,而在es7的草案中。ES6的class中只有静态方法,没有静态属性。
  static defaultProps = {
    name: 'demo'
  }

  render(){
    return <h1>This is my {this.props.name}</h1>
  }
}

es6定义默认props的正确方式:

class MyDemo extends React.Component {
  constructor(props) {
    super(props);
  }
  render() {
    return <h1>This is my {this.props.name}</h1>
  }
}
//由于是用ES6 class语法创建组件,其内部只允许定义方法,而不能定义属性,class的属性只能定义在class之外。所以defaultProps要写在组件外部。
MyDemo.defaultProps = {
  name: 'demo'
};

解决方案:

将babel设置为es7的转码方式

// Install babel
npm install babel-core babel-loader --save-dev

// For ES6/ES2015 support
npm install babel-preset-es2015 --save-dev

// If you want to use JSX
npm install babel-preset-react --save-dev

// If you want to use experimental ES7 features
npm install babel-preset-stage-0 --save-dev

在项目根目录配置.babelrc文件

{
  "presets": ["es2015", "stage-0"],
  "plugins": ["transform-runtime"]
}

如果使用webpack的话,如下配置

loaders:[
          {
            test: /\.js[x]?$/,
            exclude: /node_modules/,
            loader: 'babel-loader' ,
            query:{
              presets:['es2015','stage-0','react'],
              plugins:['transform-runtime']
            },
           }
          ]

加入stage-0后就能尝试es7语法了,static也能在class内部定义属性了~

版权声明:本文为李维亮博主的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:http://www.liweiliang.com/840.html

标签: reactjs

评论已关闭