如何在React Native中创建年份范围



我试图创建一个下拉视图,使用户能够选择他们的出生日期。我已经完成了使用虚拟数据构建组件,但是我如何使用date-fns实现年/月/日数据模块?

我所做的到目前为止,我建立下拉和工作很好,我如何能用真实日期数据代替虚拟数据斗争?

下拉组件:

const days = [
{ num: '1', key: '1' },
{ num: '2', key: '2' },
{ num: '3 ', key: '3' },
{ num: '4', key: '4' },
{ num: '5 ', key: '5' },
];
const Dropdown = ({ label, data }) => {
const [selecteday, setSelecteday] = useState({ item: '' });
const DropdownButton = useRef();
const [visible, setVisible] = useState(false);

const toggleFunction = () => {
visible ? setVisible(false) : openDropdown();
};
const openDropdown = () => {

setVisible(true);
};
const onItemPress = item => {
setSelecteday(item);
console.log(item);
setVisible(false);
};
const renderItem = ({ item }) => (
<TouchableOpacity style={styles.item} onPress={() => onItemPress(item)}>
<Text style={styles.buttonText}>{item.num}</Text>
</TouchableOpacity>
);
const renderDropdown = () => {
return (
<SafeAreaView style={styles.dropdown}>
<FlatList
data={days}
renderItem={renderItem}
keyExtractor={(item, index) => index.toString()}
/>
</SafeAreaView>
);
};
return (
<>
<View style={{zIndex: 10}} >
<TouchableOpacity
onPress={() => toggleFunction()}
ref={DropdownButton}
style={styles.button}
>
<Text style={styles.buttonText}>
{' '}
{selecteday.item === '' ? label : selecteday.num}
</Text>
<MaterialCommunityIcons name="chevron-down" color={'#58abc8'} size={16} />
{visible == true ? renderDropdown() : null}
</TouchableOpacity>

</View>
{ visible ? <View 
style={styles.modal}>
<TouchableOpacity
style ={styles.overlay}
onPress={toggleFunction}
></TouchableOpacity>
</View>: null}
</>
);
};

要获取日期、月份和年份,可以创建如下函数

const getDays = (month, year) => {
if (month <= 12 && month >= 1) {
const daysCount = new Date(year, month, 0).getDate();
console.log('daysCount--', daysCount);
const daysAr = Array(daysCount).fill('').map((element, index) => {
return {
key: index + 1 + '',
num: index + 1,
}
})
console.log(daysAr);
}
}
const getMonth = () => {
const monthCount = 12; //this is always 12 so can pass static
const monthsAr = Array(monthCount).fill('').map((element, index) => {
return {
key: index + 1 + '',
num: index + 1,
}
})
console.log(monthsAr);
}
const getYears = () => {
const yeasCount = 200;//you can pass more then 200
const yearsAr = Array(yeasCount).fill('').map((element, index) => {
return {
key: 1900 + index + '',
num: 1900 + index,
}
})
console.log(yearsAr);
}
useEffect(() => {
const selectedMonth = 5;
const selectedYear = 2022;
getMonth();
getYears();
getDays(selectedMonth, selectedYear); //first select year, month and pass selected month and year here.
}, [])

所以你必须选择年然后月然后根据你选择的月份你会得到月中的天数并转换成所需的数组

最新更新