Due I refactor my code to ES6, I move all defaults to SomeClass.defaultProps = { ... }
.
Suppose a situation, when there is a class hierarchy, and I need to keep some defaults to whole hierarchy. But the problem is that defaultProps
not work for classes that are extended:
class AbstractComponent extends React.Component {
constructor(props) { super(props) }
}
class OneOfImplementations extends AbstractComponent {
constructor(props) { super(props) }
}
//Problem: hierarchy defaults doesn't work
AbstractComponent.defaultProps = { name: 'Super' }
Fiddle example
P.S. I'm wondering where is the best place to keep mons (variables/functions) for the whole hierarchy? Maybe do something like this at AbstractComponent
:
constructor(props) {
super(_.assign(props, {
monValue: 128,
monCallback: _.noop
}));
}
But the problem is that's bee impossible to override one of properties from a subclass
Due I refactor my code to ES6, I move all defaults to SomeClass.defaultProps = { ... }
.
Suppose a situation, when there is a class hierarchy, and I need to keep some defaults to whole hierarchy. But the problem is that defaultProps
not work for classes that are extended:
class AbstractComponent extends React.Component {
constructor(props) { super(props) }
}
class OneOfImplementations extends AbstractComponent {
constructor(props) { super(props) }
}
//Problem: hierarchy defaults doesn't work
AbstractComponent.defaultProps = { name: 'Super' }
Fiddle example
P.S. I'm wondering where is the best place to keep mons (variables/functions) for the whole hierarchy? Maybe do something like this at AbstractComponent
:
constructor(props) {
super(_.assign(props, {
monValue: 128,
monCallback: _.noop
}));
}
But the problem is that's bee impossible to override one of properties from a subclass
class OneOfImplementations extends AbstractComponent {
I'm fairly sure I saw spicyj saying should be avoided, i.e. everything should extend React.Component
– Joshua
Commented
Oct 30, 2015 at 10:18
@decorator
syntax might be the preferred option - github./facebook/react/issues/5010
– Joshua
Commented
Oct 30, 2015 at 10:20
Alternatively if you're using the stage: 0 stage: 2
preset in Babel (or the transform directly) you can use es7's proposed static property:
class AbstractComponent extends React.PureComponent {
static defaultProps = { name: 'Super' }
// Bonus: you can also set instance properties like this
state = {
someState: true,
}
// ^ Combined with new arrow binding syntax, you often don't need
// to override the constructor (for state or .bind(this) reasons)
onKeyPress = () => {
// ...
}
}
It seems like the order of declaration of the "defaultProps" property is important:
class AbstractComponent extends React.Component {
constructor(props) { super(props) }
render() {
return <div>Prop: [ {this.props.name} ]</div>
}
}
AbstractComponent.defaultProps = { name: 'Super' }
class ComponentImpl1 extends AbstractComponent {
constructor(props) { super(props) }
}
// works
http://jsfiddle/jwm6k66c/103/