react-native - 如何从 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"
},
解决方案
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}
/>
);
}
}
推荐阅读
- google-apps-script - 用于打印 pdf 和发送电子邮件的 Apps 脚本忽略了 Google Sheet 分页符。如何在原始 Google 表格中保留分页符?
- data-cleaning - 数据框单元格内重复数据的数据清理
- javascript - 如何使固定元素成为条形?
- ndepend - 如何使用 NDepend 计算方法的度量响应
- javascript - 当 Jinja 模板用于向 onclick 函数提供多个参数时,“输入意外结束”
- android - Android 动画 - 为什么 fromXDelta 有负值?
- node.js - Node.js - 导入第三方库时出错
- flutter - 无论如何我可以显示一个 Stack 小部件的所有内容,它有一个动态创建的定位小部件列表作为它的孩子?
- javascript - 正则表达式匹配 C# 和 javascript 中的 end_of_line/newline 差异
- adsense - 如果在我的 AdSense 主页上找不到 PIN 验证卡,如何验证 Adsense PIN?