Umb*_*bro 13 javascript css reactjs react-select
尝试向 react-select 中的选项添加图标。我从文件england.svg, 中导入了 svg 图标germany.svg。我创建customSingleValue并放入
<Select components={{ SingleValue: customSingleValue }} />
Run Code Online (Sandbox Code Playgroud)
显示标签,但不显示图标。
演示在这里:https : //stackblitz.com/edit/react-q19sor
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'));
Run Code Online (Sandbox Code Playgroud)
Pen*_*Liu 21
我找到了解决方法。我的技术类似于@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"));
Run Code Online (Sandbox Code Playgroud)
以防万一有人想在 中使用具有多重选择的图标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>;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12662 次 |
| 最近记录: |