需求
自定义封装的一个带样式的modal,不想再写state控制visible了,只想用最简单的函数调用来弹出, showModal(config),传入配置,调用,因为modal内容很简单,就是一个confirm
Taro.showModal就可以办到,但是样式不支持定制,所以只能自己写一个函数了
参考:
https://www.swvq.com/article/detail/4012
解决:
我们写h5页面的时候,如果要办到上面的方式,需要从react dom中导出render方法以及unmountComponentAtNode方法,然后用js在内存中创建一个div,把组件render到这个div里面,document.body再addpendChild这个div
同时div会被存到全局或者一个变量上,卸载的时候remove掉,同时unmountComponentAtNode掉这个dom上的react组件
那么Taro也是如此
import { render, unmountComponentAtNode } from '@tarojs/react';
const useCustomModal = () => {
const dom = useRef<any>();
const showModal = (modalProps = {} as ModalProps) => {
if (!dom.current) {
const view = document.createElement('view');
const pages = Taro.getCurrentPages();
const currentPage = pages[pages.length - 1]; // 获取当前页面对象
const path = currentPage.$taroPath;
const pageElement = document.getElementById(path);
render(<ConfirmModal {...modalProps} visible />, view);
dom.current = view;
pageElement?.appendChild(view);
}
};
const closeModal = () => {
// const currentPages = Taro.getCurrentPages();
// const currentPage = currentPages[currentPages.length - 1];
// const path = currentPage.$taroPath;
// const pageElement = document.getElementById(path);
unmountComponentAtNode(dom.current);
dom.current?.remove();
dom.current = null;
};
return {
showModal,
closeModal,
};
};
网友评论