3 回答

TA貢獻1943條經(jīng)驗 獲得超7個贊
我找到了解決方法。我的技術(shù)類似于@canda:
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"));

TA貢獻1803條經(jīng)驗 獲得超3個贊
以防萬一有人想在 中使用多選圖標,react-select可以使用以下代碼:
const { MultiValue } = components;
const MultiValueOption = (props) => {
return (
<MultiValue {...props}>
<img
src={require("./" + props.data.icon)}
style={{ width: 36 }}
alt={props.data.label}
/>
<span>{props.data.value}</span>
</MultiValue>
);
};
<Select
options={options}
components={{
Option: IconOption,
MultiValue: MultiValueOption,
}}
isMulti={true}
></Select>;

TA貢獻1816條經(jīng)驗 獲得超6個贊
我認為問題在于您實際上并未導入 SVG。如果您嘗試<IconFlagGermany/>
在代碼中的任何地方直接使用,它會因以下消息而嚴重崩潰:
元素類型無效:應(yīng)為字符串(對于內(nèi)置組件)或類/函數(shù)(對于復(fù)合組件)但得到:未定義。您可能忘記從定義組件的文件中導出組件,或者您可能混淆了默認導入和命名導入。
它目前沒有崩潰,因為我認為您的customSingleValue
功能沒有按照您的預(yù)期工作(還沒有研究它,但很確定它被竊聽了)。
如果您希望能夠以這種方式導入 SVG,您需要在 Webpack(或您選擇的打包器)中設(shè)置一個合適的加載器。也許是這樣的:https : //www.npmjs.com/package/react-svg-loader
但是,另一種解決方案是將您的 SVG 正確導出為組件,就像從您的代碼中分叉的這個演示中一樣:https : //stackblitz.com/edit/react-5gvytm
添加回答
舉報