繁体   English   中英

如何在 StoryBook 和 React TypeScript 中创建动态 Material UI Icon Atom?

[英]How to create a dynamic Material UI Icon Atom in StoryBook and React TypeScript?

我将StoryBookReactTypeScriptMaterial UI一起使用。 我想创建一个动态行为的Icon Atom ,以便它可以呈现我想要作为prop传入的图标。

现在,我正在使用下面提到的方法,但这存在一些问题。

  1. 我无法更改特定故事的图标。 这不是我想要的动态行为。
  2. 我还想将一些props (例如fontSizecolor )传递给我的Material UI Icon ,以便它可以根据props的值使用它们进行不同的渲染。

我希望我的组件按照上述两点运行。 请帮忙 !!

Icon.stories.tsx文件

import React from "react";
import { ComponentStory, ComponentMeta } from "@storybook/react";
import MyIcon from "./Icon";
import AccessTimeIcon from "@mui/icons-material/AccessTime";
import PersonOutlineIcon from "@mui/icons-material/PersonOutline";

export default {
  title: "Atoms/MyIcon",
  component: MyIcon,
  argTypes: {
    color: {
      options: [
        "primary",
        "secondary",
        "warning",
        "error",
        "info",
        "success",
        "action",
      ],
      control: { type: "radio" },
    },
    fontSize: {
      options: ["small", "medium", "large"],
      control: { type: "radio" },
    },
  },
} as ComponentMeta<typeof MyIcon>;

const Template: ComponentStory<typeof MyIcon> = (args) => <MyIcon {...args} />;

export const Clock = Template.bind({});
Clock.args = {
  fontSize: "medium",
  color: "primary",
  materialIcon: <AccessTimeIcon />,
};

export const Person = Template.bind({});
Person.args = {
  fontSize: "large",
  color: "warning",
  materialIcon: <PersonOutlineIcon />,
};

Icon.tsx文件

import React from "react";
import type { IconProps } from "@mui/material/Icon";

interface MyIconProps extends IconProps {
  materialIcon: React.ReactElement;
}

const MyIcon = ({ materialIcon, fontSize, color }: MyIconProps) => {
  return <>{materialIcon}</>;
};
export default MyIcon;

一种方法是使用像material-icons-react这样的库,它提供了一个可以使用自定义道具渲染的反应组件。

import MaterialIcon, {colorPalette} from 'material-icons-react';

<MaterialIcon icon="dashboard" />

// different sizes
<MaterialIcon icon="dashboard" size='large' />
<MaterialIcon icon="dashboard" size={100} />

// colours
<MaterialIcon icon="dashboard" color={colorPalette.amber._200} />
<MaterialIcon icon="dashboard" color={colorPalette.amber.A700} />
<MaterialIcon icon="dashboard" color='#7bb92f' />

另一种方法是通过 Google Web Fonts 脚本包含素材图标。

将此添加到您的 html 入口点:

<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

然后您可以使用material-icons class 名称并将图标名称放在元素内:

<span class="material-icons">access_time_icon</span>

您可以将此渲染放在您的 Icon 组件中并传递您想要的任何样式道具。

请注意,如果您使用其他图标变体,例如轮廓,您需要为每个变体添加单独的字体并使用不同的 class ,例如material-icons-outlined

 <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> <span class="material-icons">access_time_icon</span>

暂无
暂无

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

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