将按钮和弹窗封装成一个组件,可以大大提高 React 代码的可重用性、可维护性和可扩展性。以下是示例代码:
import React, { useState } from "react";
import { Button, Modal } from "antd";
const MixWay = (props) => {
const [visiable, setVisiable] = useState(false);
const onOk = () => {
console.log("编写自己的onOk逻辑");
closeModal();
};
const closeModal = () => {
setVisiable(false);
};
return (
<>
<Button onClick={() => setVisiable(true)}>按钮+弹窗</Button>
<Modal
title="按钮+弹窗"
open={visiable}
onOk={onOk}
onCancel={closeModal}
afterClose={closeModal}
>
<p>弹窗内容</p>
</Modal>
</>
);
};
export default MixWay;
封装成一个组件后,我们可以轻松地复用该组件并根据需要进行扩展。
比如下面两个回放按钮
按钮
单批次回放
单接口批量回放
两者弹窗内容基本一致,只是单接口批量回放需要指定接口,单批回放不需要指定接口
所以将它封装成一个组件
https://juejin.cn/post/7130623457993162759
https://opensource.ebay.com/nice-modal-react/#real
使用https://github.com/ebay/nice-modal-react,它帮助我们快速创建弹框,写起来更加简洁
import React from "react";
import NiceModal, { useModal } from "@ebay/nice-modal-react";
import { Modal } from "antd";
const MyModal = NiceModal.create((props) => {
const { name } = props;
const modal = useModal();
const onOk = () => {
console.log("编写自己的onOk逻辑");
modal.hide();
};
return (
<Modal
title="Hello Antd"
open={modal.visible}
onOk={onOk}
onCancel={modal.hide}
afterClose={modal.remove}
>
Greetings: {name}!
</Modal>
);
});
MyModal.propTypes = {};
export default MyModal;
import React from "react";
import { Button } from "antd";
import NiceModal from "@ebay/nice-modal-react";
import MyModal from "./MyModal";
const AntdSample = () => {
return (
<>
<Button onClick={() => NiceModal.show(MyModal, { name: "Nate" })}>
Show Modal
</Button>
</>
);
};
export default AntdSample;
import React from "react";
import ReactDOM from "react-dom/client";
import App from "./App";
import NiceModal from "@ebay/nice-modal-react";
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
<React.StrictMode>
<NiceModal.Provider>
<App />
</NiceModal.Provider>
</React.StrictMode>
);
这段代码使用了 NiceModal
和 useModal
,这是 eBay 开发的一个 React 组件库,能够帮助我们快速创建模态框(Modal)。使用它有以下好处:
以上两种编写弹窗的方式,方式二使用 nice-modal-react
更加简洁,不需要手动编写显示关闭逻辑。