首页 > 解决方案 > 让 Storybook react-docgen-typescript-loader 使用 typescript 道具

问题描述

我正在尝试使用react-docgen-typescript-loader我的 TypeScript Props 在 Storybook 中生成我的道具文档,但它没有将任何内容填充到withInfo插件中。

我正在使用 create-react-app 的 TypeScript 风格,并且我正在遵循多种不同的配置方法,.storybook/webpack.config.js但似乎没有任何效果。

这是我当前的配置:

.storybook/webpack.config.js

module.exports = ({ config, mode }) => {
  config.module.rules.push({
    test: /\.(ts|tsx)$/,
    use: [
      {
        loader: require.resolve('babel-loader'),
        options: {
          presets: [['react-app', { flow: false, typescript: true }]],
        }
      },
      require.resolve("react-docgen-typescript-loader"),
    ]
  });
  config.resolve.extensions.push('.ts', '.tsx');
  return config;
};

.storybook/config.ts

import { configure } from '@storybook/react';
// automatically import all files ending in *.stories.js
const req = require.context('../', true, /.stories.tsx$/);
function loadStories() {
  req.keys().forEach(filename => req(filename));
}
configure(loadStories, module);

故事/button.stories.tsx

import * as React from 'react';

import { storiesOf } from '@storybook/react';
import { withInfo } from '@storybook/addon-info';
import Button from '../src/components/Button';

storiesOf('Button', module)
    .addDecorator(withInfo)
    .add('continue', () => <Button buttonType="submit">Hello Button</Button>, { info: { inline: true } })
    .add('back', () => <Button buttonType="reset">Hello Button</Button>, { info: { inline: true } });

src/components/Button.tsx

import React from 'react';

interface Props {
    buttonType: Button.Type;
}

const Button: React.FunctionComponent<Props> = (props) => {
    const getStyles = (buttonType: string): {color: string} => {
        if (buttonType === 'reset') {
            return { color: 'red' };
        }
        if (buttonType === 'submit') {
            return { color: 'green' };
        }
        return { color: 'green' };
    };

    const { buttonType, children } = props;

    return <button type={buttonType} style={getStyles(buttonType)}>{children}</button>;
};

export default Button;

此配置目前没有问题,但我仅将其视为 Storybook 中的信息输出: 故事书截图

标签: reactjstypescriptcreate-react-appstorybook

解决方案


使用命名导入有一些区别,这对我有用:

import React, {FC} from 'react' ...

const Button: FC<Props> = (props) => {


推荐阅读