gpt4 book ai didi

react-native - 使用 react-native-community/datetimepicker,如何在 Android 上显示日期时间选择器?

转载 作者:行者123 更新时间:2023-12-04 11:17:27 25 4
gpt4 key购买 nike

对于 iOS,库 react-native-community/datetimepicker支持日期时间模式,在该模式下显示日期和时间选择器。

但是,此模式不适用于 Android。

是否有一种解决方法可以显示 2 个连续的选择器,一个用于日期,另一个用于时间?

class ShiftTimingScreen extends Component {

state = {
dateTimePickerVisible: false,
dateOrTimeValue: new Date(),
};

render() {
return (
<View>
<TouchableOpacity
onPress={() => this.setState({ dateTimePickerVisible: true, })}
>
<Input
label='Shift Starts At'
placeholder={"01/01/2019 - 09:00 AM"}
editable={false}
value={this.state.dateOrTimeValue.toLocaleDateString()}
/>
</TouchableOpacity>

{this.state.dateTimePickerVisible &&
(<DateTimePicker
mode={"datetime"} // THIS DOES NOT WORK ON ANDROID. IT DISPLAYS ONLY A DATE PICKER.
display='default' // Android Only
is24Hour={false} // Android Only
value={defaultShiftStartDateTime}

onChange={(event, value) => {
this.setState({
dateOrTimeValue: value,
dateTimePickerVisible: Platform.OS === 'ios' ? true : false,
});

if (event.type === "set")
console.log("value:" , value);
}}
/>)}
</View>
);
}
}

export default ShiftTimingScreen;

最佳答案

我使用下面的代码来实现使用 react-native-community/datetimepicker 的日期和时间选择包裹。我希望它有帮助。引用 here详情。

const [date, setDate] = useState(
props.item.time ? new Date(props.item.time) : new Date() // to set default from props or current date
);
const [time, setTime] = useState(
props.item.time ? new Date(props.item.time) : new Date() // to set default from props or current date
);
const [mode, setMode] = useState('date');
const [show, setShow] = useState(false);

const onChange = (event, selectedValue) => {
setShow(Platform.OS === 'ios');
if (mode == 'date') {
const currentDate = selectedValue || new Date();
setDate(currentDate);
setMode('time');
setShow(Platform.OS !== 'ios'); // to show time
} else {
const selectedTime = selectedValue || new Date();
setTime(selectedTime);
setShow(Platform.OS === 'ios'); // to hide back the picker
setMode('date'); // defaulting to date for next open
}
};
const showMode = currentMode => {
setShow(true);
setMode(currentMode);
};

const showDatePicker = () => {
showMode('date');
};
return
(<View>
<TouchableOpacity onPress={showDatePicker}>
<Text style={styles.title}>{formatDate(date, time)}</Text>
</TouchableOpacity>
{show && (
<DateTimePicker
value={date}
minimumDate={Date.parse(new Date())}
display='default'
mode={mode}
onChange={onChange}
/>
)}
</View>);


const formatDate = (date, time) => {
return `${date.getDate()}/${date.getMonth() +
1}/${date.getFullYear()} ${time.getHours()}:${time.getMinutes()}`;
};

关于react-native - 使用 react-native-community/datetimepicker,如何在 Android 上显示日期时间选择器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58925515/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com