Is it good practice to create basic components and then expand them in React?

I am just learning React and I am writing components using ES7 syntax. My idea is to create a basic component that will contain some methods that I want all derived components to have. For example, I want to implement valueLink without mixin for two-way binding to all my components. Here is my idea:

class MyComponent extends React.Component { bindTwoWay(name) { return { value: this.state[name], requestChange: (value) => { this.setState({[name]: value}) } } }; } 

 class TextBox extends MyComponent { state = { val: '' }; render() { return (<div> <input valueLink={this.bindTwoWay('val')}/> <div>You typed: {this.state.val}</div> </div>) } } 

And everything works fine. However, I could not find much information about this method. This is not about valueLink, it was just an example. The idea is to have some methods in the base component and then extend that component so that the derived components have all of these methods, such as the normal OOP method. So I just wanted to know if this is great, or there are some flaws that I don’t know about. Thanks.

+6
source share
1 answer

This is perfectly normal, this is just basic inheritance. The danger of using inheritance to replace mixins is that there is no multiple inheritance, so you cannot pass your TextBox functions from multiple base classes, as if you were giving it several mixins. To get around this, you can use component composition . In your case, the composition will not work directly, as you defined in the example, but there is a workaround to this.

First you need to define a composite component

 export default (ComposedComponent) => { class MyComponent extends React.Component { constructor(props, state) { super(props, state); this.state = { val: '' }; } bindTwoWay(name) { return { value: this.state[name], requestChange: (value) => { this.setState({[name]: value}) } }; } render() { return ( <ComposedComponent {...this.props} {...this.state} bindTwoWay={this.bindTwoWay.bind(this)} /> } } } return MyComponent } 

And then you define your component where you need some common functions.

 import compose from 'path-to-composer'; class TextBox extends React.Component { render() { return ( <div> <input valueLink={this.props.bindTwoWay('val')}/> <div>You typed: {this.props.val}</div> </div> ) } } export default compose(TextBox) 

I have not tested this, but it should work.

+3
source

All Articles