我在 monorepo 中使用故事书。在我的根文件夹中preview.js有这个:
export const decorators = [
(Story) => {
const theme = createTheme("violet", "gray");
const GlobalStyles = createGlobalStyle`
*{padding: 0; margin: 0; box-sizing: border-box;}
ul{ list-style: none}
`;
return (
<ThemeProvider theme={theme}>
<GlobalStyles />
<Story />
</ThemeProvider>
);
},
];
Run Code Online (Sandbox Code Playgroud)
useState当我在组件中
使用装饰器时,我得到,Storybook preview hooks can only be called inside decorators and story functions.
故事:
export const Default = () => {
let items = [
{ id: "1", name: "one" },
...
];
const [inpItems, setItems] = useState(items);
return (
<ComboBox
items={inpItems}
onInputValueChange={({ inputValue }) => {
setItems(allItems.filter((item) => item.name.includes(inputValue)));
}}
itemToString={(item) => item?.name}
/>
);
};
Run Code Online (Sandbox Code Playgroud)
当我注释掉装饰器时,一切正常。我究竟做错了什么?
这个错误是因为装饰器是函数,而不是组件。即使您有 JSX,它也被称为 asmyDecorator()而不是<MyDecorator />; 完全绕过React。
您必须创建一个单独的组件来保存该useState钩子,然后您可以在装饰器函数中渲染该组件。
根据我的经验,这可能会导致问题,因为有时每次渲染都会调用装饰器函数 4 次或更多次。
| 归档时间: |
|
| 查看次数: |
2207 次 |
| 最近记录: |