getDefaultProps 不是獲取預設props,而是設定預設props,主要用在ES5的React寫法中
getInitialState 不是獲取預設State,而是設定初始的state,主要是用在ES5的React寫法中
下面是ES5和ES6的寫法對比
//ES5寫法 var Video = React.createClass({ getDefaultProps: function(){ return { autoPlay: false, maxLoops: 10 } }, getInitialState: function(){ return { loopsRemaining: this.props.maxLoops } }, propTypes: { autoPlay: React.PropTypes.bool.isRequired, maxLoops: React.PropTypes.number.isRequired, posterFrameSrc: React.PropTypes.string.isRequired, videoSrc: React.PropTypes.string.isRequired } }) //ES6寫法 class Video extends React.Component { static defaultProps = { autoPlay: false, maxLoops: 10 } static propTypes = { autoPlay: React.PropTypes.bool.isRequired, maxLoops: React.PropTypes.number.isRequired, posterFrameSrc: React.PropTypes.string.isRequired, videoSrc: React.PropTypes.string.isRequired } //建構函式寫法 constructor(props){ this.state = { ... } } //非建構函式寫法 state = { loopsRemaining: this.props.maxLoops } } //元件外部寫法 Video.defaultProps = { autoPlay: false, maxLoops: 10 }