首页 > 解决方案 > 如何从 json react-native-material-dropdown 获取 id

问题描述

react-native-material-dropdown在我的反应原生项目中使用过。我正在从 API 获取数据。

对不起,我的英语很差。

  fetch('xxxx.json', {  
          method: 'POST',
          headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
          }
        }).then((response) => response.json())
        .then((responseJson) => {
          var count = Object.keys(responseJson.cities).length;
          for(var i=0;i<count;i++){
            //console.warn(responseJson.cities[i].name) // I need to add 
            //these names to dropdown
            this.state.drop_down_data.push({ value: responseJson.cities[i].name,id:responseJson.cities[i].id });
          }
          //this.setState({ drop_down_data });
        })
        .catch((error) => {
          console.error(error);
        });

和下拉代码

<Dropdown
            label='City'
            data={this.state.drop_down_data}
            onChangeText={this.onCityChange.bind(this)}
          />

和更改方法问题在这里

onCityChange(val,ind,data){ fetch('xxxx/'+ cityid +'/towns.json', {  
      method: 'POST',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
      }
    }).then((response) => response.json())
    .then((responseJson) => {
      this.setState({drop_down_data2: []});
      var count = Object.keys(responseJson.towns).length;
      for(var i=0;i<count;i++){
        //console.warn(responseJson.towns[i].name) // I need to add 
        //these names to dropdown
        //
        this.state.drop_down_data2.push({ value: responseJson.towns[i].name,id:responseJson.towns[i].id });
      }
      //this.setState({ drop_down_data });
    })
    .catch((error) => {
      console.error(error);
    });
  }

在这里,我想去城市 id.value 来了,但 id 没有来,或者我不知道去 id。

如果我能得到身份证,我可以向城镇发帖请求。

我怎么能这样做?

和一些json数据

 {
            "id": 1,
            "name": "Adana",
            "alpha_2_code": "TR-01"
        },
        {
            "id": 2,
            "name": "Adıyaman",
            "alpha_2_code": "TR-02"
        },

标签: react-nativedropdown

解决方案


onChangeText方法有 3 个参数(值、索引、数据)

数据 = 完整数组

index = 选择的当前项目索引

您可以通过此代码获取 id

onChangeText = (value, index, data) => {
    const cityId = data[index].id;
    console.log("cityId", cityId);
  };

完整的示例代码

import React, { Component } from "react";
import { Dropdown } from "react-native-material-dropdown";

const data = [
  {
    value: "City1",
    id: 1
  },
  {
    value: "City2",
    id: 2
  },
  {
    value: "City3",
    id: 3
  }
];

export default class Example extends Component {
  onChangeText = (value, index, data) => {
    const cityId = data[index].id;
    console.log("cityId", cityId);
  };

  render() {
    return (
      <Dropdown
        label="Favorite Fruit"
        data={data}
        style={{ marginTop: 50 }}
        onChangeText={this.onChangeText}
      />
    );
  }
}


推荐阅读