gpt4 book ai didi

javascript - 如何在 react-select 的选项中添加图标?

转载 作者:行者123 更新时间:2023-11-28 19:15:31 24 4
gpt4 key购买 nike

尝试将图标添加到 react-select 中的选项。我从文件 england.svggermany.svg 导入了 svg 图标。我创建了 customSingleValue 并将其放入

<Select components={{ SingleValue: customSingleValue }} />

显示标签,但不显示图标。

此处演示: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'));

最佳答案

我找到了解决问题的方法。我的技术类似于 @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"));

关于javascript - 如何在 react-select 的选项中添加图标?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58449403/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com