如何在 React Native 中显示选定的时间

How can I show the selected time in React Native

首先,大家好。这是我的第一个问题。

我正在尝试在 React Native 中使用时间选择器。我从 GitHub 上的 repo 安装了软件包。但是我无法在文本组件中显示时间?我该怎么办?

const Example = (props) => {
  
    const [isDatePickerVisible, setDatePickerVisibility] = useState(false);

 
    const showDatePicker = () => {
      setDatePickerVisibility(true);
  };

    const hideDatePicker = () => {
      setDatePickerVisibility(false);
  };

    const handleConfirm = (date) => {
       console.warn("A date: ", date);
       settimeShow(date)

       hideDatePicker();
  };

  return (
    <View>
       <Button title="Show Time Picker" onPress={showDatePicker} />
       <Text>
         ?
       </Text>

    <DateTimePickerModal
      isVisible={isDatePickerVisible}
      mode="time"
      onConfirm={handleConfirm}
      onCancel={hideDatePicker}
    />

  </View>
  );
};

enter image description here

https://github.com/mmazzarolo/react-native-modal-datetime-picker

您可以在参数 date 中获取日期文本。在 handleConfirm 中将日期保存在一个 state 中并在文本中显示 :)

import React, { Component } from "react";
import { Button, View } from "react-native";
import DateTimePicker from "react-native-modal-datetime-picker";
 
export default class DateTimePickerTester extends Component {
  constructor(props) {
    super(props);
    this.state = {
      isDateTimePickerVisible: false,
      selectedDate:'',
    };
  }
 
  showDateTimePicker = () => {
    this.setState({ isDateTimePickerVisible: true });
  };
 
  hideDateTimePicker = () => {
    this.setState({ isDateTimePickerVisible: false });
  };
 
  handleDatePicked = date => {
    console.log("A date has been picked: ", date);
    setstate({selectedDate:date});
    this.hideDateTimePicker();
  };
 
  render() {
    return (
      <>
        <Button title="Show DatePicker" onPress={this.showDateTimePicker} />
        <Text>this.state.selectedDate</Text>
        <DateTimePicker
          isVisible={this.state.isDateTimePickerVisible}
          onConfirm={this.handleDatePicked}
          onCancel={this.hideDateTimePicker}
        />
      </>
    );
  }
}

您可以使用 moment 格式化您的时间然后显示它,

moment(date).format('LT') /// example : 8:30 PM