【发布时间】:2016-11-16 04:15:42
【问题描述】:
假设我有十几个或更多的 SVG 想要内联到我的 React 应用程序中。现在,我正在使用svg-react-loader 像这样导入它们。
import Svg1 from "!babel!svg-react!../../images/sdg1.svg";
import Svg2 from "!babel!svg-react!../../images/sdg2.svg";
import Svg3 from "!babel!svg-react!../../images/sdg3.svg";
import Svg4 from "!babel!svg-react!../../images/sdg4.svg";
...等等。我需要在每个事件上设置事件处理程序并悬停事件。此外,当其中一个被选中时,我想改变它的不透明度。
经过几个小时和许多失败的实验,我尝试过的唯一可行的方法是将它们全部呈现在这样的父组件中。
const Icon = React.createClass({
//Callback that updates the state of a parent component
clickHandler() {
this.props.handler(this.props.svg)
}
render() {
const icons = [
<Svg1 className="svg1" opacity={this.props.svg === this.props.currentSvg ? 1 : 0.3} />
<Svg2 className="svg2" opacity={this.props.svg === this.props.currentSvg ? 1 : 0.3} />
<Svg3 className="svg3" opacity={this.props.svg === this.props.currentSvg ? 1 : 0.3} />
<Svg4 className="svg4" opacity={this.props.svg === this.props.currentSvg ? 1 : 0.3} />
];
return (
<div className="icon" onClick={this.clickHandler}>
{icons[this.props.svg]}
</div>
);
}
});
再一次,这可行,但我确信这不是 React 想要的方式。有没有办法遍历以这种方式创建的 SVG 组件来为其分配属性?
【问题讨论】: