preface

When we do some business in the middle and background systems, we often meet the requirements of various popboxes, and these popboxes are not only a function to prevent misoperation, but often contain some forms with many fields in the popboxes.

Using Antd as an example, the most common method is to use Modal dialog components to accomplish this requirement, but the pain point of this is that it is frequent to focus on dialog visible, and the page refresh after interaction is not very friendly. Based on this, I thought of using its extension function, simple modal. method to solve this problem

Take a chestnut

const App = () => { const [isModalVisible, setIsModalVisible] = useState(false); const showModal = () => { setIsModalVisible(true); }; const handleOk = () => { setIsModalVisible(false); }; const handleCancel = () => { setIsModalVisible(false); }; return ( <> <Button type="primary" onClick={showModal}> Open Modal </Button> <Modal title="Basic Modal" visible={isModalVisible} onOk={handleOk} onCancel={handleCancel}> <p>Some contents... </p> <p>Some contents... </p> <p>Some contents... </p> </Modal> </> ); };Copy the code

From the example on the official website above, we can see that the visible property is inescapable.

First you have to open the popup, click Cancel and then manually close the popup, click OK and manually close the popup… Boy, next to putting an elephant in the fridge

This is acceptable because Modal is introduced directly inside the parent component. If it’s Modal wrapped in an external component, what about the external component introduced by the parent? For example, if you update a table, you have to refresh the page and pass in the refresh method, which is awkward

The solution

Using the concise modal. method method can solve this problem perfectly

We’ll start by creating this dialog file, which we’ll call modalOpen

function modalOpen() { const Content = ({formRef}) => { const [form] = Form.useForm() return ( <Form form={form} Ref ={formRef}> < form. Item label=" name" ="name"> <Input style={{width: 200}} /> </ form. Item> < form. Item label=" team" name="team"> Return new Promise((openSuccess,openError) => {const formRef = React.createRef(); Modal.confirm({title: 'player info ', content: < content formRef={formRef} />, okText:' confirm ', cancelText: 'cancel' onOk () {return new Promise ((resolve, reject) = > {formRef. Current. ValidateFields (). Then (values = > {/ / get the form data, Resolve () openSuccess()})})})})})} export default modalOpen;Copy the code

Then the parent page is imported and called

import modalOpen from './modal-open' ... . const createData = () => { await modalOpen(); refresh(); // Complete the asynchronous operation, refresh the page to obtain the latest data}Copy the code

Why return a promise in onOk

The last

This is the first article of this dish chicken, there are wrong places please correct, or what better way can also share!!