简体   繁体   English

如何创建绑定故事书控件参数的通用打字稿函数

[英]How to create generic typescript function that binds arguments for storybook control

How to write a generic so that the Result takes on the argument of another type supplied to the generic?如何编写泛型,以便 Result 接受提供给泛型的另一种类型的参数?

This is my example code.这是我的示例代码。

import { Story } from '@storybook/react/types-6-0';

type TKeyAny = {
  [key: string]: string; // | 'other args values here...';
};

// this fails
export const bindargs = <A extends TKeyAny, T extends Story<A>>(args: A, Template: T): T => {
  const Comp = Template.bind({});
  Comp.args = args;
  return Comp;
};

export default bindargs;

This would work but its not specific to the arguments being passed into it, which is why I'd like a generic:这会起作用,但它不是特定于传递给它的参数,这就是为什么我想要一个泛型:


// This works but I'd like this instead to be in a generic 
// export const bindargs = (args: TKeyAny, Template: Story<TKeyAny>): Story<TKeyAny> => {
//   const Comp = Template.bind({});
//   Comp.args = args;
//   return Comp;
// };

I liked the idea of a helper function so I went playing around.我喜欢辅助函数的想法,所以我去玩了。 It does cast to any inside the function but it doesn't matter for it's usage.它确实转换为函数内部的any内容,但它的用法无关紧要。

import React from "react";
import { Meta, Story } from "@storybook/react";
import { Box, BoxProps } from "./Box";

type BindTemplate = <T extends Story<any>>(template: T, args: T["args"]) => T;

const bindTemplate: BindTemplate = (template, args) => {
  const boundTemplate = (template as any).bind({});
  boundTemplate.args = args;
  return boundTemplate;
};

const config: Meta = {
  title: "Box",
  component: Box,
};

export default config;

const Template: Story<BoxProps> = (args) => <Box {...args}>lol</Box>;

export const Primary = bindTemplate(Template, {
  className: "valid",
  someInvalidProps: "invalid",
});

We use generic like this in our Storybook:我们在 Storybook 中使用这样的泛型:

Maybe you can do a similar thing也许你可以做类似的事情

import React from 'react'
import { Meta, Story } from '@storybook/react/types-6-0'

import SelectDropdown, { ISelectDropdownProps, SelectOption } from './SelectDropdown'

export default {
  title: 'Shared/Components/SelectDropdown',
  component: SelectDropdown,
  argTypes: {
    options: {
      control: {
        type: 'object',
      },
    },
(...)
} as Meta


const Template = <T extends {}>(): Story<ISelectDropdownProps<T>> => args => (
  <div
    style={{
      width: '300px',
    }}
  >
    <SelectDropdown<T> {...args} />
  </div>
)

export const Normal = Template<number>().bind({})
Normal.args = {
  options: createOptions(5),
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM