简体   繁体   English

从对象数组中获取 2 个值

[英]Getting 2 values from array of objects

I would like to select an item from the dropdown list and would like to set the state of staffId to it.我想从下拉列表中选择一个项目,并将 staffId 的状态设置为它。 I would like dropdown to show the name, but after I select the name, set the staffid to state.我想下拉显示名称,但在我选择名称后,将 staffid 设置为 state。 I would also like to achieve this without hardcoding the values in an if-else loop as I have thousands of data to work with.我还想在不对 if-else 循环中的值进行硬编码的情况下实现这一点,因为我有数以千计的数据要处理。

This is the data fetched from WebAPI and stored in a state called items这是从 WebAPI 获取并存储在名为 items 的状态中的数据

this.setState({
    items: dataSource
  staffId: ''
})

This state of items will be this.这个项目的状态将是这个。

[
    {"departmentName":"HOUSE","employeeName":"TEST1", "staffId" : "00001"},
    {"departmentName":"HOUSE","employeeName":"TEST2", "staffId" : "00002"},
    {"departmentName":"HOUSE","employeeName":"TEST3", "staffId" : "00003"}
]

I have created a dropdown in react native with just the emplyeeName.我只使用 emplyeeName 在 react native 中创建了一个下拉菜单。 I am using react-native-material-dropdown for the library.我正在为库使用 react-native-material-dropdown。 I would like to show employeeName but when a user select a name, get an id instead我想显示 employeeName 但是当用户选择一个名字时,取而代之的是一个 id

let staff = this.state.listOfEmployees.map(item => ({
        value: item.employeeName
        staffId: item.staffId
      }));
<Dropdown
    label='Staff Name'
    baseColor='#0079b5'
    data={staff}
    selectedValue={value}
    onChangeText={(staffId) => this.onChangeName(staffId)}
/>

Here in this function, I would like to set the state of staffId to the staffId of the selected value.在此函数中,我想将 staffId 的状态设置为所选值的 staffId。

onChangeName = (staffId) => {
    //set the state of staffId to the staffId of the selected value.
    //For Example, if AUNG THU 1 is selected, the state of staffId is '00001'.
    this.setState({
       staffId: staffId
    })
}

You can do this using the valueExtractor and labelExtractor props.您可以使用valueExtractorlabelExtractor道具来做到这一点。 Should look something like this:应该是这个样子:

<Dropdown
  label='Staff Name'
  baseColor='#0079b5'
  data={staff}
  selectedValue={value}
  valueExtractor={({ staffId }) => staffId}
  labelExtractor={({ employeeName }) => employeeName}
  onChangeText={(staffId) => this.onChangeName(staffId)}
/>

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

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