Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

NiceModal:重新思考 React 中的弹窗使用方式 #16

Open
worldzhao opened this issue Aug 12, 2022 · 6 comments
Open

NiceModal:重新思考 React 中的弹窗使用方式 #16

worldzhao opened this issue Aug 12, 2022 · 6 comments

Comments

@worldzhao
Copy link
Owner

在开始进入正题之前,先看看一些与弹窗有关的有趣场景 🤔。

一些有趣的真实场景

案例一:全局弹窗

image

上图是掘金的登录弹窗,未登录状态下触发该弹窗展示的时机有很多,比如:

  1. 点击 Header 上的登录按钮
  2. 文章列表页或详情页点赞以及评论文章
  3. 发沸点、评论沸点以及点赞沸点
  4. ...

开发者往往会基于第三方组件库定义一个 <LoginModal />,然后将其挂载至 Root 组件下:

function App() {
  const [visible, setVisible] = useState(false);
  const [otherLoginData, setOtherLoginData] = useState();

  // other logic ...

  return (
    <div className="app">
      <Main />
      <LoginModal
        visible={visible}
        onCancel={() => setVisible(false)}
        otherLoginData={otherLoginData}
      />
    </div>
  );
}

这样会带来一些问题:

  1. <LoginModal /> 内部逻辑在组件渲染的时候就会执行,即使弹窗处于隐藏状态
  2. 额外的复杂度。由于存在多个触发时机,需要将 setVisible 以及 setOtherLoginData 透传至 <Main /> 内部的多个子组件,你可以选择通过 props 一层一层的传递进去(鬼知道有多少层!),也可以引入工具进行状态共享,但不论怎样,这都不是一件容易的事;
  3. 随着类似的弹窗越来越多,根组件会维护很多弹窗组件的状态...天知道为什么展示一个弹窗需要在多个文件里反复横跳。

展示一个弹窗,为什么会变得如此复杂?

以上案例来自 @ebay/nice-modal-react,稍作修改

除了上述全局弹窗的场景,还有一种场景也很让人头疼。

案例二:存在分支以及依赖关系的弹窗

image

image

用户头疼,开发者也头疼

弹窗 1 确认弹出弹窗 2,取消则弹出弹窗 3,弹窗 2 以及 弹窗 3 也存在对应的分支逻辑,子孙满堂轻而易举,若按照常规声明式弹窗组件的实现,非常恐怖!

image

不那么通用的解决方案

摆脱所谓的 React 哲学:数据驱动视图(view = f(data)),回归原始的 window.confirm 以及 window.alert,很多问题迎刃而解:

let mountNode: HTMLDivElement | null = null;

LoginModal.show = (props?: LoginModalProps) => {
  if (!mountNode) {
    mountNode = document.createElement('div');
    document.body.appendChild(mountNode);
  }
  // 通过 ReactDOM.render 将组件渲染到固定的节点
  ReactDOM.render(<LoginModal {...props} visible />, mountNode);
};

LoginModal.hide = () => {
  mountNode && ReactDOM.render(<LoginModal {...props} visible={false} />, mountNode);
};

LoginModal.destroy = () => {
  // 通过 ReactDOM.unmountComponentAtNode 卸载节点
  mountNode && ReactDOM.unmountComponentAtNode(mountNode);
};

经过以上代码处理,可以直接通过 LoginModal.show({otherLoginData}) 展示弹窗(hide 以及 destroy 同理)。

对于存在依赖关系的弹窗,则可以通过返回 Promise 进行链式调用,使用方式如下,此处不过多展开。

try {
  const ret1 = await LoginModal.show({ otherLoginData });
  const ret2 = await Ohter1Modal.show();
} catch (error) {
  const ret3 = await Other2Modal.show();
}

由于该方案是通过 ReactDOM.render 将组件渲染到一个新节点,脱离了原始的 React 上下文,在某些强依赖 Context 的场景会显得有些麻烦。

可能是最好的弹窗实践

image

某天在逛 github 的时候发现了 @ebay/nice-modal-react ,让我们看看 ebay 的开发者是如何让弹窗在 React 下变得足够 Nice。

创建弹窗

import { Modal } from 'antd';
import NiceModal, { useModal } from '@ebay/nice-modal-react';

export default NiceModal.create(({ name }) => {
  // Use a hook to manage the modal state
  const modal = useModal();
  return (
    <Modal
      title="Hello Antd"
      onOk={() => modal.hide()}
      visible={modal.visible}
      onCancel={() => modal.hide()}
      afterClose={() => modal.remove()}
    >
      Hello {name}!
    </Modal>
  );
});

和原先基于 antd 自定义一个弹窗组件非常相似,只不过弹窗显隐相关的 props(如 visible/hide/remove) 是通过 useModal 获取,最外层则通过 NiceModal.create 将组件进行一层封装(高阶组件)。

使用弹窗

在使用弹窗之前,需要在Root 节点引入 <NiceModal.Provider />

import NiceModal from '@ebay/nice-modal-react';
ReactDOM.render(
  <React.StrictMode>
    <NiceModal.Provider>
      <App />
    </NiceModal.Provider>
  </React.StrictMode>,
  document.getElementById('root'),
);

随后便可在任意地方通过 NiceModal.show 展示先前自定义的弹窗:

import NiceModal from '@ebay/nice-modal-react';
import MyAntdModal from './my-antd-modal'; // created by above code

function App() {
  const showAntdModal = () => {
    // Show a modal with arguments passed to the component as props
    NiceModal.show(MyAntdModal, { name: 'Nate' })
  };
  return (
    <div className="app">
      <h1>Nice Modal Examples</h1>
      <div className="demo-buttons">
        <button onClick={showAntdModal}>Antd Modal</button>
      </div>
    </div>
  );
}

以上指引参考自 NiceModal 官方文档

经过 NiceModal 的封装,好处显而易见:

  1. 调用过程干净优雅
  2. 组件依旧存在于上下文中(可以自定义位置,默认在 Provider 下)
  3. show/hide 方法返回值为 Promise,方便链式调用(通过useModal().resolve(val)等方法改变 Promise 状态)

简单实现思路

如果你对 NiceModal 的实现原理有兴趣,那么可以思考一下我们之前的痛点是什么?案例一中描述了两大主要痛点:

  1. 根组件渲染弹窗以及维护弹窗状态过多 —— NiceModal.Provider 内统一渲染弹窗
  2. 显隐相关状态以及方法需要共享 —— 库内部维护对应状态,通过统一 API (show/hide/useModal)暴露

案例二的链式调用在脱离声明式组件后反而变得很容易,利用好 Promise 即可。

const Provider: React.FC = ({ children }) => {
  // 初始弹窗信息
  const [modals, _dispatch] = useReducer(reducer, initialState);
  dispatch = _dispatch;
  return (
    <NiceModalContext.Provider value={modals}>
      {children}
      <NiceModalPlaceholder />
    </NiceModalContext.Provider>
  );
};

const NiceModalPlaceholder: React.FC = () => {
  const modals = useContext(NiceModalContext);
  // 根据弹窗信息找到需要渲染的弹窗 ID (NiceModal.show 时更新)
  const visibleModalIds = Object.keys(modals).filter((id) =>
    Boolean(modals[id])
  );

  // 找到对应创建的高阶组件(NiceModal.show 时注册)
  const toRender = visibleModalIds
    .filter((id) => MODAL_REGISTRY[id])
    .map((id) => ({
      id,
      ...MODAL_REGISTRY[id],
    }));

  return (
    <>
      {toRender.map((t) => (
        {/* 渲染 NiceModal.create 创建的高阶组件,并注入 ID */}
        <t.comp key={t.id} id={t.id} />
      ))}
    </>
  );
};

const create =
  <P extends Record<string, unknown>>(
    Comp: React.ComponentType<P>
  ): React.FC<P & NiceModalHocProps> =>
  ({ id }) => {
    const modals = useContext(NiceModalContext);
    const shouldMount = Boolean(modals[id]);

    if (!shouldMount) {
      return null;
    }
    return (
      <NiceModalIdContext.Provider value={id}>
        {/* 找到对应 ID 的参数,传入内部真实组件 */}
        <Comp {...(modals[id].args as P)} />
      </NiceModalIdContext.Provider>
    );
  };

理解上述三个方法后,show/hide/useModal 等方法就是基于 dispatch 函数进行弹窗数据(Context) 的更新从而触发视图更新(其中 show 方法多一步注册,生成 ID 并绑定至对应的高阶组件)。

推荐阅读

@gaoryrt
Copy link

gaoryrt commented Aug 12, 2022

在中后台业务中归纳出这样的方法,将组件 promise 化:

function promisify(Render) {
  return new Promise((res, rej) => {
    const div = document.createElement('div')
    document.body.appendChild(div)
    ReactDOM.render(
      <Render
        destroy={val => {
          if (val) res(val)
          else rej()
          ReactDOM.unmountComponentAtNode(div)
          document.body.removeChild(div)
        }}
      />,
      div
    )
  })
}

@worldzhao
Copy link
Owner Author

在中后台业务中归纳出这样的方法,将组件 promise 化:

function promisify(Render) {
  return new Promise((res, rej) => {
    const div = document.createElement('div')
    document.body.appendChild(div)
    ReactDOM.render(
      <Render
        destroy={val => {
          if (val) res(val)
          else rej()
          ReactDOM.unmountComponentAtNode(div)
          document.body.removeChild(div)
        }}
      />,
      div
    )
  })
}

这个方法很赞!我们也有类似的工具函数,对于 99% 场景都足够了(也没遇到无法支撑的场景),主要是去年看到了 NiceModal,调用方式更加灵活,也解决了 Context 问题,就换 NiceModal 了。

@gaoryrt
Copy link

gaoryrt commented Aug 12, 2022

这个方法很赞!我们也有类似的工具函数,对于 99% 场景都足够了(也没遇到无法支撑的场景),主要是去年看到了 NiceModal,调用方式更加灵活,也解决了 Context 问题,就换 NiceModal 了。

以前的我:这样写是不是违反了 React 伦理,会不会坏了祖师爷立下的规矩
现在的我:去 tm 的 Thinking in React

@enclairfarron
Copy link

enclairfarron commented Aug 12, 2022

在中后台业务中归纳出这样的方法,将组件 promise 化:

function promisify(Render) {
  return new Promise((res, rej) => {
    const div = document.createElement('div')
    document.body.appendChild(div)
    ReactDOM.render(
      <Render
        destroy={val => {
          if (val) res(val)
          else rej()
          ReactDOM.unmountComponentAtNode(div)
          document.body.removeChild(div)
        }}
      />,
      div
    )
  })
}

这个方法很赞!我们也有类似的工具函数,对于 99% 场景都足够了(也没遇到无法支撑的场景),主要是去年看到了 NiceModal,调用方式更加灵活,也解决了 Context 问题,就换 NiceModal 了。

这个挂载 body 可能会有问题哦,比如在微前端的场景下,看看是不是应该弄一个类似 antd 的 getPopupContainer

@gaoryrt
Copy link

gaoryrt commented Aug 12, 2022

@enclairfarron indeed

@worldzhao
Copy link
Owner Author

worldzhao commented Aug 16, 2022

ReactDOM.render 是否改成 ReactDOM.createPortal 会更好一些

我发现很多同学对 ReactDOM.createPortal 这个方法理解有一些偏差,这个方法返回的 portal 元素依旧是需要挂载的(ReactDOM.render 调用执行就能渲染),你可以把返回的 portal 也理解成一个组件,是 Modal 和 Popup 等组件的底层,但不适用于本文面对和解决的问题。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants