我正在尝试使用babel-loader和ts-loader使用Typescript设置Storybook。
除了在React组件中使用children
之外,一切都很好:
[tsl] ERROR in .../stories/index.stories.tsx(8,56)
TS2769: No overload matches this call.
Property 'children' is missing in type '{ title: string; }' but required in type 'Props'.
下面是.storybook/main.js
文件:
module.exports = {
addons: [
"@storybook/addon-knobs",
],
stories: ["../packages/**/*.stories.tsx"],
webpackFinal: async config => {
config.module.rules.push({
test: /\.(ts|tsx)$/,
exclude: /node_modules/,
use: [
{
loader: require.resolve('ts-loader')
},
{
loader: require.resolve('babel-loader'),
options: {
presets: [
"@babel/preset-env",
"@babel/preset-react"
]
}
}
],
});
config.resolve.extensions.push('.ts', '.tsx');
return config;
}
};
下面是index.stories.tsx
文件:
import React from "react";
import Collapsible from "../src";
export default {
title: "Collapsible"
};
const content = <span>Content</span>;
export const simpleCollapsible = () => (
<Collapsible title="Collapsible">{content}</Collapsible>
);
这是Collapsible的实现:
import React, { ReactNode, useState } from "react";
import styled, { ThemeProvider } from "styled-components";
import {
BorderProps,
ColorProps,
FlexboxProps,
LayoutProps,
SpaceProps,
TypographyProps
} from "styled-system";
import Theme from "@atw/theme";
import { KeyboardArrowDown } from "@styled-icons/material";
import Box from '~/box';
import Button from '~/button';
interface Props
extends BorderProps,
ColorProps,
FlexboxProps,
LayoutProps,
SpaceProps,
TypographyProps {
children: ReactNode;
title: string;
}
const Collapsible = ({ children, title, ...rest }: Props) => {
const [isCollapsed, setIsCollapsed] = useState(false);
const handleCollapse = () => {
setIsCollapsed(!isCollapsed);
};
return (
<ThemeProvider theme={Theme}>
<Button
border="none"
padding={0}
marginBottom={2}
width={1}
textAlign="start"
onClick={handleCollapse}
{...rest}
>
<IconBox isCollapsed={isCollapsed}>
<KeyboardArrowDown size="24px" />
</IconBox>
{title}
</Button>
{!isCollapsed && (
<Box display="flex" flexDirection="column">
{children}
</Box>
)}
</ThemeProvider>
);
};
export default Collapsible;
我做错了什么吗?
4条答案
按热度按时间dbf7pr2w1#
一个可能的解决方案是利用函数组件中的默认子机制
React.FC
,它允许您挂载子对象,而无需显式地将它们作为prop包含在类型定义中。对于您的情况,这可以通过应用以下更改来实现:Working sandbox for this
ffscu2ro2#
第一步
添加React.FC:它已经为你声明了子对象。并在React中添加你的自定义Props。
你的代码应该是这样的:
const Collapsible : React.FC<Props> = ({ children, title, ...rest }) => {
第二步
yyyllmsg3#
我添加了Babel Preset Typescript,错误消失了。
这就是我的
.storybook/main.js
现在的样子:8iwquhpp4#
你有没有试
在你的组件中,用它 Package prop 。