简体   繁体   English

在反应的下拉列表中选择用户时获取ID

[英]getting the ID when user is selected in dropdown in react

I have a dropdown list in react.我有一个反应下拉列表。 in which username is getting displayed.在其中显示username my requirement is to get id instead of username when user select any value.我的要求是在用户选择任何值时获取id而不是username

在此处输入图像描述

I have below code for that.我有下面的代码。

                            <select
                                onChange={(e) => selectedUser(e)}
                                className=" form-select-control">
                                <option value="">Please select the user</option>
                                {active &&
                                    users.map((user: any) => (
                                        <option>{user.displayName}</option>
                                    ))}
                            </select>



  const selectedUser = (e: any) => {
        setUser(e.target.value);
    };

on dropdown I am getting data from API.在下拉列表中,我正在从 API 获取数据。 below is the data.下面是数据。

在此处输入图像描述

I am getting ID along with displayName (username) from API.我从 API 获取IDdisplayName (用户名)。 my question is under selectedUser method how can I get ID for selected user.我的问题是在selectedUser方法下如何获取所选用户的 ID。 is there any other way as well?还有其他方法吗?

There are several ways to achieve this.有几种方法可以实现这一点。

You need to define a key if you create DOM elements with React when you iterate through an array with .map() anyway (else you'll get a warning in the console of your browser).如果您在使用.map()遍历数组时使用 React 创建 DOM 元素,则需要定义一个key (否则您将在浏览器的控制台中收到警告)。 You can use the key to get the user.id :您可以使用key获取user.id

<select onChange={(e) => selectedUser(e)} className=" form-select-control">
    <option value="">Please select the user</option>
    {active &&
        users.map((user: any) => (
            <option key={user.id}>{user.displayName}</option>
        ))}
</select>;

const selectedUser = (e: any) => {
    setUser(e.target.key);
};

You could also save the user.id in id={user.id} and grab it via e.target.id .您还可以将user.id保存在id={user.id}并通过e.target.id获取。

You can write the code something like this您可以编写类似这样的代码

                        <select
                            onChange={(e) => selectedUser(e)}
                            className=" form-select-control">
                            <option value="">Please select the user</option>
                            {active &&
                                users.map((user: any) => (
                                    <option id={user.id}>{user.displayName}</option>
                                ))}
                        </select>



  const selectedUser = (e: any) => {
    setUser(e.target.id);
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM