[英]React Native: 'componentWillReceiveProps' clearing Dropdown Selected Value
[英]React Native dropdown api value not selected
我在反應本機應用程序中使用 react-native-element-dropdown 。 如果在 useState 中設置默認值,它可以正常工作,但它不適用於設置 api 響應值並且未在下拉列表中選擇
import { Dropdown } from "react-native-element-dropdown";
const Profile = ({ navigation, route }) => {
const [country, setCountry] = useState("");
useEffect(() => {
getUserProfile();
}, []);
const getUserProfile = async () => {
return api
.getuserprofile(locale, authValues.user.id, authValues.token)
.then((response) => {
if (response.data.status) {
setCountry(response.data.body.user.country_id);
}
})
.catch((error) => {
//console.log(error);
});
};
return (
<SafeAreaView style={globalStyles.appContainer}>
<View style={globalStyles.inputBox}>
<Text style={globalStyles.inputLabel}>Country of Residence</Text>
<Dropdown
data={CountryData}
search
maxHeight={300}
labelField="value"
valueField="key"
placeholder="Country of Residence"
searchPlaceholder={"Search..."}
value={country}
onChange={(item) => {
setCountry(item.key);
}}
/>
</View>
</SafeAreaView>
);
};
export default Profile;
我創建了一個如何在React native
上歸檔它的示例:
import * as React from 'react';
import {useState, useEffect} from 'react';
import { Text, View, StyleSheet } from 'react-native';
import Constants from 'expo-constants';
import { Dropdown } from 'react-native-element-dropdown';
import AntDesign from 'react-native-vector-icons/AntDesign';
export default function App() {
const [data, setData] = useState([{
key: 1,
value: 'Australia'
}, {
key: 2,
value: 'New Zeland'
}, {
key: 3,
value: 'The United State'
}]);
const [selectedValue, setSelectedValue] = useState(null);
const [isFocus, setIsFocus] = useState(false);
const getSelected = () => {
fetch('https://api.agify.io/?name=michael').then(res => {
setSelectedValue(3);
}).catch((err) => {
console.log(err);
})
}
useEffect(() => {
getSelected();
}, []);
return (
<View style={styles.container}>
<Dropdown
style={[styles.dropdown, isFocus && { borderColor: 'blue' }]}
data={data}
search
maxHeight={300}
labelField="value"
valueField="key"
placeholder={!isFocus ? 'Select item' : '...'}
searchPlaceholder="Search..."
value={selectedValue}
onFocus={() => setIsFocus(true)}
onBlur={() => setIsFocus(false)}
onChange={item => {
setSelectedValue(item.key);
setIsFocus(false);
}}
renderLeftIcon={() => (
<AntDesign
style={styles.icon}
color={isFocus ? 'blue' : 'black'}
name="Safety"
size={20}
/>
)}
/>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
paddingTop: Constants.statusBarHeight,
backgroundColor: '#ecf0f1',
padding: 8,
},
});
您可以從此處查看工作示例
你使用了 item.value 的 item.key
onChange={item => {
setValue(item.value);
setIsFocus(false);
}}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.