【问题标题】:How to dynamically add data(dropdown list) from api in react-native-select-dropdown?如何在 react-native-select-dropdown 中从 api 动态添加数据(下拉列表)?
【发布时间】:2021-10-18 08:56:45
【问题描述】:

我正在使用 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;
  }}
/>

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

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

【问题讨论】:

  • 您应该使用状态来处理动态数据更改并重新渲染...例如useState对于功能组件,请查看此链接:https://reactjs.org/docs/hooks-state.html
  • 你能举例说明一下吗
  • 可以映射数组,然后可以显示命名,也可以获取选中数据的id
  • @JuhiKukreja 如果我的回答对你有帮助,请采纳。

标签: javascript reactjs react-native dropdown


【解决方案1】:

这是根据您的要求从您的代码中获取的示例。在下面的代码下拉菜单中将显示国家名称,当您选择其中任何一个时,它将打印所选国家和 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>
  );
}

【讨论】:

  • 非常感谢... :}
猜你喜欢
  • 1970-01-01
  • 2022-07-22
  • 1970-01-01
  • 1970-01-01
  • 2020-07-28
  • 2017-04-15
  • 1970-01-01
  • 2014-09-27
  • 1970-01-01
相关资源
最近更新 更多