请说明React中getDefaultProps 的作用 ?

getDefaultProps是React组件的一个方法,它在React 16.3版本之后已经被弃用,对于新的代码,建议使用ES6 class的静态属性defaultProps来替代。

getDefaultProps的主要作用是为组件提供一组默认的属性值。这意味着如果父组件在使用这个组件时没有提供某个props,那么组件将使用getDefaultProps定义的默认值。

比如我们有一个Welcome组件,它接受一个name的prop:

var Welcome = React.createClass({
  getDefaultProps: function() {
    return {
      name: 'Guest'
    };
  },

  render: function() {
    return <h1>Welcome {this.props.name}</h1>;
  }
});

在这个例子中,如果我们使用<Welcome />而没有提供name prop,那么组件将渲染为”Welcome Guest”。如果我们提供了name prop,比如<Welcome name="John" />,那么组件将渲染为”Welcome John”。

在ES6 class中,你可以这样定义默认的props:

class Welcome extends React.Component {
  render() {
    return <h1>Welcome {this.props.name}</h1>;
  }
}

Welcome.defaultProps = {
  name: 'Guest'
};

这种方式的效果和getDefaultProps完全一样。

发表评论

后才能评论