在ReactJs中创建动态svg图标组件

时间:2019-06-30 17:09:53

标签: javascript reactjs svg jsx

我想为我的SVG图标创建一个React组件,但是如果我在另一个组件中多次使用此组件(具有不同的道具),它将始终呈现相同的图标。

我的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图标会呈现几次,以及如何解决?

1 个答案:

答案 0 :(得分:0)

您的代码运行良好,我已经从中创建了代码片段:

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;