Inheritance – superclass inheritance in React DEFAULTPROPS

I think some props (for example, themes) are so common in components that the processing (for the super class) to extract them makes sense. Then its default value also belongs to There.

But, what is the only way to achieve this in React?

class Base extends React.Component {
bgColor() {
switch (this.props.theme) {
case'Summer' : return'yellow'; break;
case'Autumn': return'grey'; break;
case'Winter': return'white'; break;
}
}
}
Base.defaultProps = {
theme:'autumn'
};
class Sky extends Base {
render() {< br /> return
{this.props.clouds}
;
}
}
Sky.defaultProps = {
clouds: []
};

… defaultProps is a class attribute (as opposed to an instance), and there is no inheritance.

By assigning Sky.defaultProps, you can hide the basic ones. If you want to combine them, you need to do so explicitly, for example

Sky.defaultProps = Object.assign({}, Base.defaultProps, {
clouds: []
});

< /div>

I think some props (e.g., themes) are so common in components that the process of extracting them (for superclasses) makes sense. Then its default value also belongs there .

But, what is the only way to achieve this in React?

class Base extends React.Component {
bgColor() {
switch (this.props.theme) {
case'Summer' : return'yellow'; break;
case'Autumn': return'grey'; break;
case'Winter': return'white'; break;
}
}
}
Base.defaultProps = {
theme:'autumn'
};
class Sky extends Base {
render() {< br /> return
{this.props.clouds}
;
}
}
Sky.defaultProps = {
clouds: []
};

… defaultProps is a class attribute (as opposed to an instance), and there is no inheritance.

< /p>

By assigning Sky.defaultProps, you can hide the basic ones. If you want to combine them, you need to do so explicitly, for example

< pre>Sky.defaultProps = Object.assign({}, Base.defaultProps, {
clouds: []
});

Leave a Comment

Your email address will not be published.