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
}