【问题标题】:Create dynamic svg icons component in ReactJs在 ReactJs 中创建动态 svg 图标组件
【发布时间】:2019-11-11 13:50:00
【问题描述】:

我想为我的 SVG 图标创建一个 React 组件,但如果我在另一个组件中多次使用该组件(使用不同的 props),它总是呈现相同的图标。

我的icon.js 组件:

import { ReactComponent as ArrowDown} from '../assets/icons/icons-line-arrrow-down.svg';
import { ReactComponent as ArrowUp} from '../assets/icons/icons-line-arrrow-up.svg';

const iconTypes = {
  arrowDown: ArrowDown,
  arrowUp: ArrowUp,
}

const IconComponent = ({name, ...props}) => {
  let Icon = iconTypes[name];
  return <Icon {...props} />;

};

export default IconComponent

用法:

import Icon from 'components/Icon';

有效:

class MyComponent extends React.PureComponent {
  render() {
    return (
      <div>
        <Icon name={"arrowDown"}/>
      </div>
    )}
}

它也有效:

class MyComponent extends React.PureComponent {
  render() {
    return (
      <div>
        <Icon name={"arrowUp"}/>
      </div>
    )}
}

它两次渲染ArrowDown图标:

class MyComponent extends React.PureComponent {
  render() {
    return (
      <div>
        <Icon name={"arrowDown"}/>
        <Icon name={"arrowUp"}/>
      </div>
    )}
}

所以我的问题是:为什么当我使用我的组件两次时,只有第一个 SVG 图标被渲染了多次,以及如何修复它?

【问题讨论】:

  • 您的代码运行良好...

标签: javascript reactjs svg jsx


【解决方案1】:

您的代码运行良好,我已经从中创建了代码 sn-p:

CodeSandbox

index.js

import React from "react";
import ReactDOM from "react-dom";
import Icon from "./icon";

function App() {
  return (
    <div>
      <Icon name="arrowUp" />
      <Icon name="arrowDown" />
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

icon.js

import React from "react";
import { ReactComponent as ArrowDown } from "./arrow-down.svg";
import { ReactComponent as ArrowUp } from "./arrow-up.svg";

const iconTypes = {
  arrowDown: ArrowDown,
  arrowUp: ArrowUp
};

const IconComponent = ({ name, ...props }) => {
  let Icon = iconTypes[name];
  return <Icon {...props} />;
};

export default IconComponent;

【讨论】:

    猜你喜欢
    • 2016-12-07
    • 1970-01-01
    • 2020-09-02
    • 2020-11-25
    • 2019-08-10
    • 2011-04-22
    • 2018-02-28
    • 1970-01-01
    • 2016-04-09
    相关资源
    最近更新 更多