我正在使用reactJs构建管理模板,组成整个页面的组件之一看起来像这样。
class UserManagement extends React.Component {
state = {
showDeleteModal: false
};
_toggleDeleteModal = () => {
this.setState(prevState => ({
showDeleteModal: !prevState.showDeleteModal
}));
};
onDeleteRow = () => {
console.log("delete");
};
render() {
return (
<div>
{this.state.showDeleteModal && (
<DeleteModal
title="Delete Data ?"
description="Are you sure you want to delete this data from the system ?"
onDeleteAction={this.onDeleteRow}
onToggleModal={this._toggleDeleteModal}
/>
)}
</div>
);
}
}
DeleteModal
基本上是一个模式,它会弹出并向用户显示一堆选项,用户可以根据这些模式选择选项,这是此UserManagement
中包含的许多模式之一零件。如您所见,我需要在render函数中写出DeleteModal
代码,对其他模态执行此操作会导致此页面上的多余代码可能以某种方式提取出来。
最后,我希望能够做类似的事情
答案 0 :(得分:0)
我不清楚您的问题,但希望您问如何提取DeleteModal
组件。话虽如此,这是我的想法;
class UserManagement extends React.Component {
state = {
showDeleteModal: false
};
_toggleDeleteModal = () => {
this.setState(prevState => ({
showDeleteModal: !prevState.showDeleteModal
}));
};
onDeleteRow = () => {
console.log("delete");
};
renderDeleteModal = () => (
<DeleteModal
title={"Delete Data ?"}
description={
"Are you sure you want to delete this data from the system ?"
}
onDeleteAction={this.onDeleteRow}
onToggleModal={this._toggleDeleteModal}
/>
);
render() {
return (
<React.Fragment>
{this.state.showDeleteModal && this.renderDeleteModal}
</React.Fragment>
);
}
}
答案 1 :(得分:0)
我假设您拥有的所有模态都具有相似的结构,并且由于在任何时间点仅向用户显示一个模态 您可以在具有以下字段的可重用模式下创建:
您可以尝试创建以下内容:
class UserManagement extends React.Component {
constructor(props) {
this.state = {
showModal: false,
modalTitle: "",
modalDescription: "",
modalAction: null
}
}
showDeleteModal() {
this.setState(prevState => ({
modalTitle: "Delete Data ?",
modalDescription: "Are you sure you want to delete this data from the system ?",
modalAction: this.onDeleteRow
}), this._toggleDeleteModal)
}
_toggleDeleteModal = () => {
this.setState(prevState => ({
showModal: !prevState.showModal
}))
};
onDeleteRow = () => {
console.log("delete");
};
render() {
return (
<div>
{this.state.showModal && (
<Modal
data={this.state.modal}
onToggleModal={this._toggleModal}
/>
)}
</div>
);
}
}
您可以为每个用例(例如“删除”)使用一个特定的功能来设置标题,说明等。
如果您认为我将显示的所有代码都将移至HOC,并将其导入到UserManagement组件中,则认为它们将执行静态操作,而无需UserManagement组件的输入。