我使用popper.js实现了一个Popper组件,并使用React的Portal来渲染弹出元素。
现在我想预览我的Popper组件,但是在storybook.js中无法创建portal。
这是我的解决方法。
.storybook/preview.js
import { ThemeProvider } from 'emotion-theming';
import { Global } from '@emotion/react';
import { theme, normalize } from 'custom-theme';
export const parameters = {
actions: { argTypesRegex: '^on[A-Z].*' },
controls: {
matchers: {
color: /(background|color)$/i,
date: /Date$/,
},
},
};
export const decorators = [
Story => (
<>
<ThemeProvider theme={theme}>
<Global styles={normalize} />
{Story()}
<div id="popper-root"></div>
</ThemeProvider>
</>
),
];
Portal.tsx
import { ReactNode, useMemo } from 'react';
import { createPortal } from 'react-dom';
interface IPortal {
children: ReactNode;
portalId: string;
}
const Portal = ({ children, portalId }: IPortal) => {
const portalElement = useMemo<HTMLElement | null>(
() => document.getElementById(portalId),
[portalId],
);
if (!portalElement) {
throw new Error(`Undefined Portal Id : ${portalId}`);
}
return createPortal(children, portalElement);
};
export default Portal;
捕获错误消息
有没有办法在Storybook上使用React Portal显示组件?如果没有,除了在React项目中进行测试之外,还有其他预览它的方法吗?