I want to design two reactjs
classes. Most of the code contained in the two classes is the same. An example is shown in the following code snippet. As indicated using comments, most of the handler methods share the same logic and only a few handlers differ between the two classes Items
and Clients
.
class Items/Clients extends Component {
state = {
currInput: {
// different for Items and Clients
},
data: [],
formModalOpen: false,
editMode: false
};
formModalOpenHandler = () => {
// same logic for both clients and items
};
formModalCloseHandler = () => {
this.setState({
formModalOpen: false,
currInput: {
// different for Items and Clients
},
editMode: false
});
};
inputChangeHandler = event => {
// same logic for both clients and items
};
submitHandler = operation => {
// same logic for both clients and items
};
deleteItem = (e, rowData) => {
// same logic for both clients and items
};
editItemActionHandler = (e, rowData) => {
// same logic for both clients and items
};
render() {
let func;
func = this.state.editMode
? () => this.submitHandler("edit")
: () => this.submitHandler("save");
return (
<div>
<Button
onClick={this.formModalOpenHandler}
>
Create New Item / Create New Client
</Button>
<div >
<MaterialTable
columns={// different for clients and items}
actions={// same for both clients and items}
data={this.state.data}
title="Items" / “Clients”
/>
</div>
<Modal
open={this.state.formModalOpen}
onClose={this.formModalCloseHandler}
>
<div>
// different for clients and items
//for items
<ItemForm
inputChangeHandler={this.inputChangeHandler}
value={{ ...this.state.currInput }}
submitHandler={func}
/>
//for clients
<ClientForm
value={this.state.currInput}
inputChangeHandler={this.inputChangeHandler}
submitHandler={func}
/>
</div>
</Modal>
</div>
);
}
}
export default Items/Clients;
How can I reuse the code common to both classes? This will facilitate code re-usage reducing the redundancy for better debugging in the future.
I am looking for something similar to inheritance in C++
but to the best of my knowledge reactjs does not support C++ kind inheritance.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…