我正在查看 DatePickerIOS 组件的文档,他们使用getDefaultProps()来初始化组件中的道具。
getDefaultProps: function () {
return {
date: new Date(),
timeZoneOffsetInHours: (-1) * (new Date()).getTimezoneOffset() / 60,
};
},
getInitialState: function() {
return {
date: this.props.date,
timeZoneOffsetInHours: this.props.timeZoneOffsetInHours,
};
},
使用ES6语法的相同之处是什么?因为我一直在使用:
constructor(props) {
super(props);
this.state = {
//equivalent to getInitialState is here
};
}
我应该这样做.props = {}来设置我的默认道具吗?
答案 0 :(得分:9)
见:
https://github.com/facebook/react/issues/3725
class X extends React.Component {
}
X.defaultProps = {...}
如果您使用的是babel-plugin-transform-class-properties软件包,则可以执行以下操作:
class X extends React.Component {
static defaultProps = {...}
}
答案 1 :(得分:1)
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,
}
state = {
loopsRemaining: this.props.maxLoops,
}
}