简体   繁体   English

如何使用道具渲染 SVG 组件?

[英]How to render SVG component using props?

I'm trying to render an SVG using props of a function.我正在尝试使用函数的道具渲染 SVG。 Any help on how to achieve this?关于如何实现这一目标的任何帮助?

Here is the code:这是代码:

import React from "react";
import Camera from "../icons/Camera.svg";

export default function Button(props) {
  console.log(props.icon);
  return (
    <button
      type="button"
      className="mx-auto mb-2.5 flex items-center gap-2 rounded-lg border border-gray-300 px-3.5 py-2 text-sm font-medium text-gray-700 drop-shadow-sm"
    >
      {props.icon} /* SVG ICONS GOES HERE*/
      {props.label}
    </button>
  );
}

Could try:可以试试:

import React from "react";
import Camera from "../icons/Camera.svg";

export default function Button({icon, label}) {
  return (
    <button
      type="button"
      className="mx-auto mb-2.5 flex items-center gap-2 rounded-lg border border-gray-300 px-3.5 py-2 text-sm font-medium text-gray-700 drop-shadow-sm"
    >
      {icon && <img src={Camera} alt={label} />}
    </button>
  );
}

Here is how you can add an Icon https://codesandbox.io/s/react-playground-forked-x4vsge?file=/index.js以下是如何添加图标https://codesandbox.io/s/react-playground-forked-x4vsge?file=/index.js

However, a few things when you are creating these components.但是,在创建这些组件时有一些事情。

  1. If the Icons source is an API (CMS) then you should have some predefined icons and should have your icons library build and pass just icon names.如果图标源是 API (CMS),那么您应该有一些预定义的图标,并且应该构建图标库并仅传递图标名称。
  2. If you have very limited icons build SVG icons as components and use them如果您的图标非常有限,请将 SVG 图标构建为组件并使用它们

When you use your Button component just use the SVG as a JSX当您使用 Button 组件时,只需将 SVG 用作 JSX

import Camera from "../icons/Camera.svg";

export default function App() {
  return <Button icon={<Camera />} label="Click Me" />;
}

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

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