ReactJs中的代码可重用性(继承)



我想设计两个reactjs类。这两个类中包含的大部分代码是相同的。下面的代码片段中显示了一个示例。如注释所示,大多数处理程序方法共享相同的逻辑,只有少数处理程序在两个类ItemsClients之间不同。

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;

如何重用两个类的公共代码?这将有助于代码的重复使用,减少冗余,以便在未来进行更好的调试。

我正在C++中寻找类似于继承的东西,但据我所知,reactjs不支持C++类型的继承。

ReactJS和VueJS中的继承概念大致相反,这意味着您不使用继承将父代码附加到子代码中,而是将子代码推入父代码中。

因此,您可以做的是将所有这些公共代码推送到另一个ReactJS组件中,并将它们都导入到构建在其上的另外两个父组件中

--编辑--ReactJS和VueJS中相反的继承概念被称为Composition,正如Drew-Reese在评论中提到的那样。

最新更新