我想为我的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图标会呈现几次,以及如何解决?
答案 0 :(得分:0)
您的代码运行良好,我已经从中创建了代码片段:
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;