默认道具
defaultProps 允许你为组件 props 设置默认值或回退值。当你使用固定道具从不同视图调用组件时,defaultProps 非常有用,但在某些视图中,你需要传递不同的值。
句法
ES5
var MyClass = React.createClass({
getDefaultProps: function() {
return {
randomObject: {},
...
};
}
}
ES6
class MyClass extends React.Component {...}
MyClass.defaultProps = {
randomObject: {},
...
}
ES7
class MyClass extends React.Component {
static defaultProps = {
randomObject: {},
...
};
}
getDefaultProps() 或 defaultProps 的结果将被缓存并用于确保 this.props.randomObject 具有一个值(如果父组件未指定)。