Correct Way To Inherit React Components
Solution 1:
In React, inheritance for components is severely discouraged. React is much better suited for expressing the same relationships via composition.
Here is an example of using composition:
classButtonextendsComponent {
render() {
return (
<divclassName='Button'style={{color:this.props.color }}>
{this.props.children}
</div>
)
}
}
classDeleteButtonextendsComponent {
render() {
return (
<Buttoncolor='red'>Delete</Button>
)
}
}
Note how DeleteButton
uses the look and feel of Button
without inheriting from it. Instead, Button
defines its configurable parts via props
, and DeleteButton
supplies those props. In the actual DOM, both <Button />
and <DeleteButton />
would render to a single DOM node—the recursive resolution happens at the render()
time, and this is the core idea of React.
In fact, if you don’t need lifecycle hooks or local state, you may even define components as functions:
functionButton({ color, children }) {
return (
<divclassName='Button'style={{color }}>
{children}
</div>
)
}
functionDeleteButton() {
return (
<Buttoncolor='red'>Delete</Button>
)
}
You can even mix classes with functions. This would be impossible with inheritance, but works great with composition.
As for your specific use cases:
I also have
Component2
which is basically absolutely the same, but has one additional<input/>
inside the return of its render function.
You can have your Component1
accept this.props.children
and use them in the return value of render()
method, and have Component2
render to <Component1><input /></Component>
. This is very similar to what I showed above. You also don’t have to use the children
prop—you can pass a React element in any prop, e.g. <Component1 footer={<input />} />
, and then you can use this.props.footer
inside Component1
.
I also have
Component3
, which shares same functions, but has different render() function.
If they share any other code (e.g. utilities that calculate some data), move that code outside components into a shared module, and import it from both components.
If they share any UI, extract it into yet another component, and use it from both your components.
Post a Comment for "Correct Way To Inherit React Components"