Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to realize the function of display dialog box by hook in React project

2025-02-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)05/31 Report--

This article mainly introduces "how to achieve the display dialog function of hook in the React project". In the daily operation, I believe that many people have doubts about how to achieve the function of the display dialog box in the React project. The editor consulted all kinds of materials and sorted out a simple and easy-to-use method of operation. I hope it will be helpful to answer the question of "how to achieve the display dialog function of hook in the React project". Next, please follow the editor to study!

It is not easy to use dialog boxes in React, mainly because:

The dialog box needs to be declared in the parent component to control whether it is displayed in the child component.

Passing parameters to a dialog box can only be passed in from props, which means that all state management must be in higher-level components. In fact, the parameters of this dialog box are only maintained in subcomponents. At this point, we need to use a custom event to return the parameter

The essence of these problems is how to manage the dialog box in a unified way, so as to make the business logic related to the dialog box more modular and decoupled from other business logic.

The following is just a summary of experience, not the only or best implementation:

Idea: use global state to manage all dialogs

A dialog box is essentially a window independent of other interfaces and is used to complete an independent function.

So, defining a dialog box, positioning is equivalent to defining a page with a unique URL path. It's just that the former is implemented by the pop-up layer, and the latter is the switching of the page.

The dialog box UI pop-up process is very similar to the switching of the page URL, so we can define a globally unique ID for each dialog box, and then use this ID to show or hide a dialog box and pass it parameters.

Try to design an API to manage the dialog box globally.

Assuming that the dialog we implemented is NiceModal, then our goal is to continue to use:

Const UserInfoModal = NiceModal.create ('user-info-modal', RealUserInfoModal) / / create a hook like useNiceModal to get the operator of an id dialog const modal = useNiceModal (' user-info-modal') / / display a dialog box through modal.show and pass it the parameter modal.show (args) modal.hide ()

As you can see, if there is such an API, then no matter which level of components, as long as you know the ID of a certain Modal, you can use these dialogs uniformly, instead of thinking about which level of components should be defined.

Implementation: create NiceModal components and related API

Create an action creator and reducer that handles all dialogs

Function showModal (modalId, args) {return {type: "nice-modal/show", payload: {modalId, args} function hideModal (modalId, force) {return {type: "nice-modal/hide", payload: {modalId Force}} const modalReducer = (state = {hiding: {}}, action) {switch (action.type) {case "nice-modal/show": const {modalId, args} = action.payload return {... state, / / if there is a state corresponding to modalId (i.e. args) This dialog box is displayed / / as long as there are parameters, the dialog box should be displayed. If args is not passed, use the default value true [modalId]: args in reducer | | true, / / define a hiding status Used to process dialog closes animation hiding: {... state.hiding, [modalId]: false,}} case "nice-modal/hide": const {modalId, force: boolean} = action.payload / / the dialog box is really removed only when force Otherwise, it is hiding hiding return action.payload.force? {... state, [modalId]: false, hiding: {[modalId]: false}}: {... state Hiding: {[modalId]: true}} default: return state}}

The main idea of this code is to store each dialog box state and parameters through Redux's store. Two action are designed here to show and hide the dialog box.

In particular, a state such as hiding is added to handle the animation of the dialog box closing process.

According to the order of use, first implement createNiceModal

Using container mode, return null directly when the dialog box is not visible, so nothing is rendered

Make sure that even if 100 dialog boxes are defined on the page, it does not affect performance.

CreateNiceModal = (modalId, Comp) = > {return (props) = > {const {visible, args} = useNiceModal (modalId) if (! visible) return null return}} / / use const MyModal = createNiceModal ('my-modal', () = > {return (Hello NiceModal)})

Implement useNiceModal, encapsulating some logic according to id.

Make the action of Redux more convenient to use and encapsulate the operation of store in it, so as to realize the logical reuse of dialog state management.

Const modalCallbacks = {} const useNiceModal = (modalId) = > {const dispatch = useDispatch () / / Encapsulation Redux action is used to display dialog const show = useCallback ((args) = > {dispatch (showModal (modalId, args))}, [dispatch ModalId]) / / Encapsulation Redux action is used to hide the dialog (force: boolean) const hide = useCallback ((force) = > {dispatch (hideModal (modalId, force))}, [dispatch ModalId]) const args = useSelector ((s) = > s [modalId]) const hiding = useSelector ((s) = > s.hiding [modalId]) / / as long as there are parameters, the dialog box should be displayed If args is not passed, use the default value true return {args, hiding, visible:! args, show, hide}} in reducer

In this way, we have implemented a global dialogue management framework such as NiceModal.

Use as follows:

Import {Button} from 'antd'import NiceModal, {createNiceModal, useNiceModal} from ". / NiceModal" const MyModal = createNiceModal ("my-modal") () = > {return (Hello World)}) function MyModalExample () {const modal = useNiceModal ("my-modal") return (modal.show ()} > Show my modal)} return value of the processing dialog box

If the two UI modes of dialog box and page are basically the same, independent windows complete independent logic. But when it comes to user interaction, there are some differences:

The dialog box may need to return a value to the caller

On the other hand, page switching generally does not care about the result of page execution.

Based on the above NiceModal implementation logic, now consider how to get the caller to get the return value.

We can regard the user's operation in the dialog box as an asynchronous operation logic, then after the user completes the operation of the contents of the dialog box, the user thinks that the asynchronous operation logic is completed. So we can use Promise to accomplish this logic.

So, the API we are going to implement is as follows:

Const modal = useNiceModal ('my-modal') / / implement a promise API to handle the return value modal.show (args). Then (res = > {})

In fact, it is not difficult to implement such a mechanism, that is, to provide a method like modal.resolve in the implementation of useNiceModal, the Hook, which can go to the Promise returned by resolve modal.show.

The core idea of the code is to connect the show and resolve functions through Promise. So the location of the two function calls is different, so we use a local temporary variable to hold the resolve callback function.

/ using a resolve callback function of object cache promise const modalCallbacks = {}; export const useNiceModal = (modalId) = > {const dispatch = useDispatch (); const show = useCallback ((args) = > {return new Promise ((resolve) = > {/ / when the dialog box is displayed, return promise and temporarily store the resolve method modalCallbacks [modalId] = resolve; dispatch (showModal (modalId, args);}) }, [dispatch, modalId],); const resolve = useCallback ((args) = > {if (modalCallbacks [modalId]) {/ / if there is a resolve callback function, then call modalCallbacks [modalId] (args); / / make sure that you can only resolve delete modalCallbacks [modalId];}}, [modalId],) / / other logic. / / take resolve as part of the return value return {show, hide, resolve, visible, hiding};}; at this point, the study on "how to display the dialog box function in hook in the React project" is over, hoping to solve everyone's doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report