Material-UI<自动完成/>标签与选项值不同 [英] Material-UI <Autocomplete /> different label than option value

查看:46
本文介绍了Material-UI<自动完成/>标签与选项值不同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个材料UI <自动完成/> 组件我正在使用您可以在其中输入某人的姓名的组件,它将提供可供选择的人的列表.这是一个非常标准的用例,但是我需要表单中的所选项目与标签不同.

I have a Material-UI <Autocomplete /> component I am using where you can type in someone's name and it will provide a list of people to select from. This is a pretty standard use case, however I need the selected item in the form to be different than the label.

当前,如果您选择标记为"John Smith"的条目,则文本字段将填充"John Smith".相反,我想用该用户的ID填充文本字段.

Currently if you pick the entry labelled "John Smith", the text field will be filled with "John Smith". Instead, I want to fill the text field with that user's ID.

用于自动完成的数据是这样的对象数组:

The data for autocomplete is an array of objects like this:

{ "name": "John Smith", "id": 123456789 }

如何使自动填充组件将用户ID放在文本字段中而不是用户标签中?

How can I make the autocomplete component put the user ID in the text field instead of the user label?

推荐答案

您可以自定义 renderOption Material-UI 自动完成

You can customize renderOption props in Material-UI Autocomplete

呈现该选项,默认情况下使用getOptionLabel.
签名:功能(选项:T,状态:对象)=>ReactNode
选项:要呈现的选项.
状态:组件的状态.

Render the option, use getOptionLabel by default.
Signature: function(option: T, state: object) => ReactNode
option: The option to render.
state: The state of the component.

至于代码

getOptionLabel={option => option.name}
renderOption={(option) => <span>{option.name}</span>}

请参阅正式文档中的演示

这篇关于Material-UI&lt;自动完成/&gt;标签与选项值不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆