网站搜索

reactjs - 在 Storybook 的全局装饰器中调用 React Hooks


我想为所有故事调用自定义 React Hook,但是,我不确定应该在哪里声明。我想调用的自定义 Hook 必须在上下文提供者中。

有没有方法为所有故事声明上下文提供者和自定义钩子?

import React from 'react';
import { useCustomHooks } from './custom';
import { ThemeProvider } from 'styled-components';

export const decorators = [
  (Story) => (
    useCustomHooks() // I wanna call custom hooks here but not working because not in provider
    <ThemeProvider theme="default">
      <Story />
    </ThemeProvider>
  ),
];

答案#1

是的,在 .storybook/preview.js 中:

import { addDecorator } from '@storybook/react';

addDecorator((Story) =>
  <MotionLazyContainer>
    <ThemeProvider>
      <Story />
    </ThemeProvider>
  </MotionLazyContainer>
);