如何从 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。

如果我能得到ID,我可以发布城镇的请求。

我该怎么做?

和一些 JSON 数据

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

onChangeTextMethod 有 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}
/>
);
}
}

最新更新