Ear*_*han 7 reactjs react-select
如何传递选项以在选择中预览图像。我有国家选择,我想预览国旗。在这种情况下,我不知道如何传递“选项”对象。
var countries =
[
{value: 'me', label: 'Montenegro'},
{value:'rs',label: 'Serbia' }
];
<Select name={"nationality_" + passenger.passengerId}
value={passenger.nationality}
options={countries}/>
Run Code Online (Sandbox Code Playgroud)
GG.*_*GG. 29
Gaurav 的答案有效,但你失去了通过标签搜索选项的能力。
\nformatOptionLabel相反,使用允许您更改默认格式的属性:
const countries = [\n { value: \'me\', label: \'Montenegro\', image: \'\xe2\x80\xa6\' },\n { value:\'rs\', label: \'Serbia\', image: \'\xe2\x80\xa6\' }\n];\n\n<ReactSelect\n value={passenger.nationality}\n options={countries}\n formatOptionLabel={country => (\n <div className="country-option">\n <img src={country.image} alt="country-image" />\n <span>{country.label}</span>\n </div>\n )}\n/> \nRun Code Online (Sandbox Code Playgroud)\n来自文档:
\n\n\n\n
formatOptionLabel将菜单和控件中的选项标签格式化为 React 组件
\n
https://react-select.com/props#select-props
\n小智 12
将国家/地区中的标签更改为 html。
const options = [
{ value: 'chocolate', label: <div><img src={copyIcon} height="30px" width="30px"/>Chocolate </div> },
{ value: 'strawberry', label: 'Strawberry' },
{ value: 'vanilla', label: 'Vanilla' },
];Run Code Online (Sandbox Code Playgroud)
像这样添加这将在选项中添加图像以供选择。
小智 6
就我而言,当我想呈现国家/地区标志时,我只需将第三个值添加到单个选项中,如下所示:
var countries =
[
{value: 'me', label: 'Montenegro', flagPath: <relative-path-to-flag>},
{value:'rs',label: 'Serbia', flagPath: <relative-path-to-flag> }
];
Run Code Online (Sandbox Code Playgroud)
如果您想在下拉选项中呈现标志,请使用“component.Option”,但它不会在所选选项中显示标志,为此您必须使用“component.SingleValue”,例如:
singleOption = (props: OptionProps<any>) => (
<components.Option {...props}>
{props.data.flagPath? DO SOMETHING WITH YOUR ICON HERE : null}
{props.label}
</components.Option>)
singleValue = (props: any) => (
<components.SingleValue {...props}>
{props.data.flagPath?DO SOMETHING WITH YOUR ICON HERE: null}
</components.SingleValue>
Run Code Online (Sandbox Code Playgroud)
)
然后你必须在 Select 中使用组件,像这样:
<Select
...
components={{
Option: this.singleOption,
SingleValue: this.singleValue
}}
/>
Run Code Online (Sandbox Code Playgroud)
希望它能帮助某人解决这个问题:)
| 归档时间: |
|
| 查看次数: |
20613 次 |
| 最近记录: |