ES7 引入了static属性和方法定义的概念。与支持 ES7 的转译器一起,这些可以在 React中用于指定验证器和默认值props,如下所示:
export default class ComponentOne extends React.Component {
static propTypes = {
foo: React.PropTypes.string
}
static defaultProps = {
foo: 'bar'
}
// ...
}
这非常方便,但是当子类发挥作用时会变得很棘手。例如,假设将以下模块添加到与ComponentOne上述相同的代码库中:
export default class ComponentTwo extends ComponentOne {
static propTypes = {
baz: React.PropTypes.number
}
static defaultProps = {
baz: 42
}
// ...
}
我想ComponentTwo“继承”其超类的属性验证器和默认值,ComponentOne. 取而代之的是propTypes,defaultProps在.ComponentTwoComponentOneComponentOne
由于super是对当前类原型的引用,并且static应该引用直接挂在原型上的值,我认为这可能有效:
import _ from 'lodash';
export default class ComponentTwo extends ComponentOne {
static propTypes = _.merge(super.propTypes, {
baz: React.PropTypes.number
});
}
但是,这会产生一个错误,可能来自 Babel: Parsing error: 'super' outside of function or class。
这有效,但不是很便携:
export default class ComponentTwo extends ComponentOne {
static propTypes = Object.assign({
baz: React.PropTypes.number
}, ComponentOne.propTypes);
}
有没有其他方法可以更干净/可重用地做到这一点?