У меня есть компонент React / TypeScript. В Button.tsx:
type Props = {
type:
| "primary"
| "secondary"
| "tertiary"
}
const Button = React.FC<Props> = ({ type }) => {
const color = (() => {
switch (type) {
case "primary":
return 'red';
case "secondary":
return 'blue';
case "tertiary":
return 'green';
default:
throw new Error("A backgroundColor condition was missed");
}
})();
return(
<button style={{ background: color }}>Im a button</button>
)
}
Что я могу использовать в других компонентах. В Page.tsx:
const Page = () => {
return(
<div>
<h1>Heading</h1>
<Button type="primary" />
</div>
)
}
В Storybook мне нужно использовать все значения типа. В Button.stories. js:
const types = [
"primary",
"secondary",
"tertiary",
];
export const AllButtons = () => {
return(
types.map(type=>{
<Button type={type} key={type} />
})
)
}
Вместо того, чтобы повторять «первичный», «вторичный», «третичный», есть ли способ экспортировать их из Button.tsx? Таким образом, если добавлен новый тип, он будет автоматически добавлен в файл Storybook.
Я мог бы использовать перечисление в Button.tsx:
export enum Types {
primary = "primary",
secondary = "secondary",
tertiary = "tertiary",
}
type Props = {
type: Types;
};
Однако тогда компоненты, которые используют Button, не могут просто передать строку, вам придется импортировать перечисление каждый раз, когда вы используете Button, что не стоит компромисса. В Page.tsx:
import { Type } from './Button'
const Page = () => {
return(
<div>
<h1>Heading</h1>
<Button type={Type.primary} />
</div>
)
}