我正在使用React-Bootstrap和TypeScript构建一个CRUD应用程序。我的Users
页面应该有两个模态,分别对应Create User
和Edit User
按钮。我编写了编辑按钮来打开Edit Modal
,它运行良好。我尝试使用相同的方法打开Create Modal
,但它打开的是相同的编辑模态,而不是创建模态。
有人能告诉我应该如何更改代码以使Create User
按钮正常工作吗?
这是我的密码。
用户.tsx
const Users = (props: Props) => {
const [userList, setUserList] = useState<IList[]>([]);
const [show, setShow] = useState(false);
const [selected, setSelected] = useState(Object);
const [updatedItem, setUpdatedItem] = useState();
const getUsers = async () => {...};
useEffect(() => {...}, [updatedItem]);
const handleShow = () => setShow(true);
const closeHandler = () => setShow(false);
const userHandler = async (user: any) => {...};
const updateHandler = async (user: any) => {...};
const handleEdit = (selected: any) => {...};
const createModal = (
<>
<Modal show={show} onHide={closeHandler} className="modal">
<Modal.Header closeButton>
<Modal.Title>Create User</Modal.Title>
</Modal.Header>
<Modal.Body>
<UserForm
userHandler={userHandler}
closeHandler={closeHandler}
updateHandler={updateHandler}
formUpdate={false}
userList={""}
/>
</Modal.Body>
</Modal>
</>
);
const editModal = (
<>
<Modal show={show} onHide={closeHandler} className="modal">
<Modal.Header closeButton>
<Modal.Title>Edit User</Modal.Title>
</Modal.Header>
<Modal.Body>
<UserForm
userHandler={userHandler}
closeHandler={closeHandler}
updateHandler={updateHandler}
formUpdate={true}
userList={selected}
/>
</Modal.Body>
</Modal>
</>
);
return (
<div>
{/* <UserForm
userHandler={userHandler}
closeHandler={closeHandler}
updateHandler={updateHandler}
userList={""}
/> */}
<Button variant="danger" type="button" onClick={handleShow}>
Create User
</Button>
{createModal}
{userList.length > 0 ? (
<UserTable
deleteHandler={deleteHandler}
handleEdit={handleEdit}
userHandler={userHandler}
closeHandler={closeHandler}
updateHandler={updateHandler}
userList={userList}
/>
) : (
""
)}
{editModal}
</div>
);
};
export default Users;
用户表单.tsx
type Props = {
userHandler: (user: object) => void;
userList: any;
updateHandler: (user: object) => void;
formUpdate?: boolean;
closeHandler: () => void;
};
class UserForm extends Component<Props, State> {
componentDidUpdate() {...}
addUser = (e: any) => {...};
update = () => {...};
render() {
return (
<div>
<Form onSubmit={this.addUser}>
...
<Modal.Footer>
{this.props.formUpdate ? (
<>
<Button
variant="outline-secondary"
className="modal-btn"
onClick={this.props.closeHandler}
>
Cancel
</Button>
<Button
variant="danger"
className="modal-btn"
type="button"
onClick={this.update}
>
Edit User
</Button>
</>
) : (
<>
<Button
variant="outline-secondary"
className="modal-btn"
onClick={this.props.closeHandler}
>
Cancel
</Button>
<Button
variant="danger"
className="modal-btn"
type="submit"
onClick={this.addUser}
>
Create User
</Button>
</>
)}
</Modal.Footer>
</Form>
</div>
);
}
}
export default UserForm;
1条答案
按热度按时间gijlo24d1#
您在两个模型中使用了相同的布尔标志
show
。您需要创建两个不同的状态来管理两个模型。现在,当您使用setShow(true)
时,它将使两个模型都可见,并在创建用户模型的顶部编辑模态。用于创建用户
用于创建用户
然后更新代码以使用两种不同的状态而不是仅使用一种状态。