目标:当用户从DatePicker中选择“时间”时,显示时间列表。
问题:它仅显示一个时间,而不是时间列表。
我可以从日期选择器中选择时间。当我单击“确定”时,所选时间将显示在清单中。但是,选择新时间后,旧时间将被替换。这导致列表上仅显示1次。
我在下面添加了该应用的屏幕截图。
因此,将理解与解决该问题有关的任何帮助。
下面的代码段:
import React, { Component } from 'react';
import { View, Text, StyleSheet, TouchableOpacity, ScrollView, FlatList } from 'react-native';
import DatePicker from '@react-native-community/datetimepicker';
import Feather from 'react-native-vector-icons/Feather';
import moment from 'moment';
export default class FrCreateScreen extends Component {
constructor(props) {
super(props);
this.state = {
//Time
appointmentTime: new Date(moment()),
modeAppointmentTime: 'time',
showAppointmentTime: false,
textAppointmentTime: moment().format('h:mm a').toString(),
//new timeSlots
timeSlots: [],
}
}
//[ timePicker start]
setAppointmentTime = (event, appointmentTime, textAppointmentTime, timeSlots) => {
appointmentTime = appointmentTime || this.state.appointmentTime;
textAppointmentTime = textAppointmentTime || moment(appointmentTime).format('h:mm a').toString();
this.setState({
showAppointmentTime: Platform.OS === 'ios' ? true : false,
appointmentTime,
textAppointmentTime,
//newly added
timeSlots: [{ time: textAppointmentTime }],
});
}
showTime = (modeAppointmentTime, textAppointmentTime, timeSlots) => {
textAppointmentTime = moment(this.state.appointmentTime).format('h:mm a').toString();
this.setState({
showAppointmentTime: true,
modeAppointmentTime,
textAppointmentTime,
//newly added
timeSlots: [{ time: textAppointmentTime }],
})
}
timePicker = () => {
this.showTime('time');
}
//[ timePicker end ]
getAppointmentTimePage() {
//const { timeSlots, selectedValue } = this.state;
const {
appointmentTime,
showAppointmentTime,
modeAppointmentTime,
textAppointmentTime
} = this.state;
return (
<View>
<Text style={[styles.title, { marginTop: 20 }]}>Select Appointment Time:</Text>
<View style={styles.container}>
{<TouchableOpacity onPress={this.timePicker}>
<Text style={styles.textDate}>
{textAppointmentTime}
</Text>
</TouchableOpacity>}
{showAppointmentTime && <DatePicker
value={appointmentTime}
mode={modeAppointmentTime}
onChange={this.setAppointmentTime}
minimumDate={new Date(moment())}
/>}
</View>
<TouchableOpacity style={styles.addContainer}>
<Text style={styles.addText}>Add Appointment</Text>
</TouchableOpacity>
</View>
);
}
render() {
return (
<ScrollView>
{this.getAppointmentTimePage()}
<TouchableOpacity>
<View style={styles.row}>
<FlatList
data={this.state.timeSlots}
keyExtractor={(times) => times.time}
renderItem={({ item }) => {
return (
<View>
<Text style={styles.textTime}>{item.time}</Text>
<TouchableOpacity>
<Feather name="trash" style={styles.icon} />
</TouchableOpacity>
</View>
);
}}
/>
</View>
</TouchableOpacity>
</ScrollView>
)
};
};
最佳答案
您要做的唯一更改是在数组中追加项目,而不是更新数组对象。
timeSlots: [...this.state.timeSlots,{ time: textAppointmentTime }],
错误是您将数组视为对象。
关于javascript - React Native:使用FlatList和DatePicker创建时间列表,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59407616/