gpt4 book ai didi

reactjs - 如何声明SVG组件的props类型? [React、TypeScript 和 Webpack]

转载 作者:行者123 更新时间:2023-12-04 02:33:52 27 4
gpt4 key购买 nike

基本上,我想要做的是将一个 SVG 图标导入到我的 React 组件中并为其添加 Prop 。赞 size="24px"使其作为一个组件更加灵活。或者通过添加 className 使其可使用 CSS 进行编辑 Prop (所以我可以添加例如悬停 Prop )。
由于这是我第一次在 Webpack 中使用 TypeScript,我对如何为 SVG 元素声明类型感到困惑,但出现错误(如下所示)
由于包含 SVG 的方法有很多种,我决定将其作为 ReactComponent 导入。
菜单图标.svg

<svg width="24" height="24" viewBox="0 0 24 24">
<path fill="currentColor" fillRule="evenodd" d="M4.5 5h15a.5.5 0 1 1 0 1h-15a.5.5 0 0 1 0-1zm0 6h15a.5.5 0 1 1 0 1h-15a.5.5 0 1 1 0-1zm0 6h15a.5.5 0 1 1 0 1h-15a.5.5 0 1 1 0-1z"></path>
</svg>
header.tsx(这里我想要我的 svg 图标)
import React from 'react';
import MenuIcon from '../assets/menu-icon.svg';

const Header: React.SFC = () => {
return (
<header className="c-header u-side-paddings">
<MenuIcon className="c-header__icon" /> // <-- className prop doesn't match provided type
</header>
);
};

export default Header;
index.d.ts(因此 .svg 文件可以被视为一个组件)
declare module '*.svg' {
import React = require('react');
export const ReactComponent: React.SFC<React.SVGProps<SVGSVGElement>>;
const src: string;
export default src;
}
添加 className支持 MenuIcon SVG 组件会导致错误:
(JSX attribute) className: string
Type '{ className: string; }' is not assignable to type 'IntrinsicAttributes'.
Property 'className' does not exist on type 'IntrinsicAttributes'.ts(2322)
到目前为止我的理解
  • 我可以将 svg 组件包装在一个 div 中,并添加一个 className像这样:<div className="c-header__icon"><MenuIcon/></div>但我觉得这是一个不雅的解决方案,并不是一个好的做法
  • 我从 this answer 学到的SVG Prop 不是字符串,因为它们是 SVGAnimatedString对象。所以:
  • 我尝试创建 .tsx 文件而不是 .svg(那时我不需要 index.d.ts 文件),但只有在 className 时才有效。的类型是 string .此外,我不确定将 SVG 图标存储在具有不同扩展名的文件中是否是一个好习惯 .svg .在我看来,这并不利于清晰。如果我错了,请告诉我实际好的做法是什么。示例如下:
  •     import React from 'react';

    interface MenuIcon {
    className?: SVGAnimatedString;
    }

    export class MenuIcon extends React.PureComponent<MenuIcon> {
    render() {
    return (
    <svg width="24" height="24" viewBox="0 0 24 24">
    <path fill="currentColor" fillRule="evenodd" d="M4.5 5h15a.5.5 0 1 1 0 1h-15a.5.5 0 0 1 0-1zm0
    6h15a.5.5 0 1 1 0 1h-15a.5.5 0 1 1 0-1zm0 6h15a.5.5 0 1 1 0 1h-15a.5.5 0 1 1 0-1z"></path>
    </svg>
    );
    }
    }
    我觉得我缺乏一些基础知识,我真的很难弄清楚我应该关注什么,因为有几个主题组合在一起

    最佳答案

    我一直面临这个问题,这个解决方案对我来说很好:

    declare module "*.svg" {
    import { ReactElement, SVGProps } from "react";
    const content: (props: SVGProps<SVGElement>) => ReactElement;
    export default content;
    }

    此外,我正在使用 @svgr/webpack作为 SVG 加载器和 Next.js

    关于reactjs - 如何声明SVG组件的props类型? [React、TypeScript 和 Webpack],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62715379/

    27 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com