如何从react-native-select-dropdown中的api动态添加数据(下拉列表)?

Juh*_*eja 2 javascript reactjs react-native dropdown

我正在使用react-native-select-dropdown并静态设置数据数组,但不知道如何使用id从api动态设置数据数组

代码 :

  const countries = ["Egypt", "Canada", "Australia", "Ireland"]

  <SelectDropdown
  data={countries}
  // defaultValueByIndex={1}
  // defaultValue={'Egypt'}
  onSelect={(selectedItem, index) => {
    console.log(selectedItem, index);
  }}
  defaultButtonText={"Select"}
  buttonTextAfterSelection={(selectedItem, index) => {
    return selectedItem;
  }}
  rowTextForSelection={(item, index) => {
    return item;
  }}
/>
Run Code Online (Sandbox Code Playgroud)

如何动态设置国家数组列表,我需要所选项目的标题和 ID,从 api 获取数据是:

const countries = [
  {namd: 'Egypt', id: 1},
  {namd: 'Canada', id: 2},
  {namd: 'Australia', id: 3},
  {namd: 'Ireland', id: 4},
];
Run Code Online (Sandbox Code Playgroud)

Man*_*ntu 7

这是根据您的要求摘自您的代码的示例。在下面的代码中,下拉菜单将显示国家/地区名称,当您选择其中任何一个时,它将打印所选的国家/地区和 ID。您可以使用 useState 挂钩来管理 API 调用。我已经向您展示了如何管理下拉菜单的响应的示例。

你可以查看我刚刚制作的零食示例 - https://snack.expo.dev/hRpKm2bdg

const countries = [
  {namd: 'Egypt', id: 1},
  {namd: 'Canada', id: 2},
  {namd: 'Australia', id: 3},
  {namd: 'Ireland', id: 4},
];


export default function App() {
  return (
    <View>
     <SelectDropdown
    data={countries}
    onSelect={(selectedItem, index) => {
        console.log('selected Country name ->>>>',selectedItem.namd)
        console.log('selected Country Id ->>>>',selectedItem.id)
    }}
    buttonTextAfterSelection={(selectedItem, index) => {
        // text represented after item is selected
        // if data array is an array of objects then return selectedItem.property to render after item is selected
        return selectedItem.namd
    }}
    rowTextForSelection={(item, index) => {
        // text represented for each item in dropdown
        // if data array is an array of objects then return item.property to represent item in dropdown
        return item.namd
    }}
     />
    </View>
  );
}
Run Code Online (Sandbox Code Playgroud)