问题
尝试在 react-select 中向选项添加图标。 我从 england.svg、Germany.svg 文件中导入了 svg 图标。 我创建了 customSingleValue 并将其放入:
<Select components={{ SingleValue: customSingleValue }} />
可以显示标签但是不能显示图标。示例代码如下:
import Select from 'react-select'
import { ReactComponent as IconFlagEngland } from "./england.svg";
import { ReactComponent as IconFlagGermany } from "./germany.svg";
const options = [
{ value: 'England', label: 'England', icon: <IconFlagEngland/> },
{ value: 'Germany', label: 'Germany', icon: <IconFlagGermany/> }
]
const customSingleValue = ({ options }) => (
<div className="input-select">
<div className="input-select__single-value">
{ options.icon && <span className="input-select__icon">{ options.icon }</span> }
<span>{ options.label }</span>
</div>
</div>
);
class App extends Component {
constructor() {
super();
this.state = {
name: 'React'
};
}
render() {
return (
<Select
defaultValue={ options [0] }
options={ options }
/*styles={ selectCustomStyles }*/
/*onChange={ changeSelectHandler }*/
components={ {SingleValue: customSingleValue } }
/>
);
}
}
render(<App />, document.getElementById('root'));
解决方案
我找了一个非常有用的方法来解决:
import React, { Component } from "react";
import { render } from "react-dom";
import "./style.css";
import Select, { components } from "react-select";
const options = [
{ value: "England", label: "England", icon: "england.svg" },
{ value: "Germany", label: "Germany", icon: "germany.svg" }
];
const { Option } = components;
const IconOption = props => (
<Option {...props}>
<img
src={require('./' + props.data.icon)}
style={{ width: 36 }}
alt={props.data.label}
/>
{props.data.label}
</Option>
);
class App extends Component {
constructor() {
super();
this.state = {
name: "React"
};
}
render() {
return (
<Select
defaultValue={options[0]}
options={options}
components={{ Option: IconOption }}
/>
);
}
}
render(<App />, document.getElementById("root"));