I have essentially two components with the same logic in the componentWillReseiveProps method and in some other methods. How can I apply inheritance or how can I avoid duplicating logic?
- Try to look for the answer before asking the question stackoverflow.com/a/35678424/4882290 - Fomina Ekaterina
- @ Dmitry Zavarzin, if there is an answer to ruSO - send an alarm to a duplicate. If there is an enSO - translate the answer, without forgetting to put a link to the source, and all other questions will be closed as a duplicate - Grundy
|
1 answer
Inheritance between components in a reactor is discouraged.
There are three options:
To transfer the duplicated code prop
Select a base component and, transferring props, create more specific components. An example from the documentation with Dialog and SignUpDialog:
function Dialog(props) { return ( <FancyBorder color="blue"> <h1 className="Dialog-title"> {props.title} </h1> <p className="Dialog-message"> {props.message} </p> {props.children} </FancyBorder> ); } class SignUpDialog extends React.Component { constructor(props) { super(props); this.handleChange = this.handleChange.bind(this); this.handleSignUp = this.handleSignUp.bind(this); this.state = {login: ''}; } render() { return ( <Dialog title="Mars Exploration Program" message="How should we refer to you?"> <input value={this.state.login} onChange={this.handleChange} /> <button onClick={this.handleSignUp}> Sign Me Up! </button> </Dialog> ); } handleChange(e) { this.setState({login: e.target.value}); } handleSignUp() { alert(`Welcome aboard, ${this.state.login}!`); } }- Move frequently used non-UI operations to a separate class.
|