@aakagi/datetimepicker 中文文档教程
React Native DateTimePicker
React Native 日期 & iOS 和 Android 的时间选择器组件
iOS | |
Android | |
Table of Contents
- React Native DateTimePicker
- Getting started
- General Usage
- Props
mode
(optional
)display
(optional
,Android only
)onChange
(optional
)value
(required
)maximumDate
(optional
)minimumDate
(optional
)timeZoneOffsetInMinutes
(optional
,iOS only
)locale
(optional
,iOS only
)is24Hour
(optional
,Android only
)neutralButtonLabel
(optional
,Android only
)minuteInterval
(optional
,iOS only
)
- Migration from the older components
- Contributing to the component
- Manual installation
- Running the example app
Getting started
npm install @react-native-community/datetimepicker --save
或
yarn add @react-native-community/datetimepicker
RN >= 0.60
如果您使用的是 RN >= 0.60,则仅从 ios 目录运行 pod install
。 然后重建你的项目。
RN < 0.60
对于 RN < 0.60,您需要使用 react-native link
链接依赖项:
react-native link @react-native-community/datetimepicker
然后从 ios 目录运行 pod install
并重建您的项目。
如果这不起作用,请参阅手动安装。
General Usage
import DateTimePicker from '@react-native-community/datetimepicker';
或
const DateTimePicker = require('@react-native-community/datetimepicker');
Basic usage with state
import React, {useState} from 'react';
import {View, Button, Platform} from 'react-native';
import DateTimePicker from '@react-native-community/datetimepicker';
const App = () => {
const [date, setDate] = useState(new Date(1598051730000));
const [mode, setMode] = useState('date');
const [show, setShow] = useState(false);
const onChange = (event, selectedDate) => {
const currentDate = selectedDate || date;
setDate(currentDate);
setShow(Platform.OS === 'ios' ? true : false);
};
const showMode = currentMode => {
setShow(true);
setMode(currentMode);
};
const showDatepicker = () => {
showMode('date');
};
const showTimepicker = () => {
showMode('time');
};
return (
<View>
<View>
<Button onPress={showDatepicker} title="Show date picker!" />
</View>
<View>
<Button onPress={showTimepicker} title="Show time picker!" />
</View>
{show && (
<DateTimePicker
testID="dateTimePicker"
timeZoneOffsetInMinutes={0}
value={date}
mode={mode}
is24Hour={true}
display="default"
onChange={onChange}
/>
)}
</View>
);
};
export default App;
Props
请注意,此库目前在 iOS 上公开来自
UIDatePicker
的功能和 DatePickerDialog + TimePickerDialog 在 Android 上。这些本机类仅提供有限的配置,而您作为开发人员可能需要数十种可能的选项。 因此,如果支持本机视图不支持您的要求,则此库将无法实现您的要求。 当您打开带有功能请求的问题时,请记录是否(或如何)使用上述本机视图来实现该功能。 如果这些视图不支持您的需求,则此类功能请求将因不可操作而被关闭。
mode
(optional
)
定义选择器的类型。
可能值列表:
"date"
(default foriOS
andAndroid
)"time"
"datetime"
(iOS
only)"countdown"
(iOS
only)
<RNDateTimePicker mode="time" />
display
(optional
, Android only
)
定义 Android 选择器的视觉显示,iOS 将被忽略。
可能值列表:
"default"
"spinner"
"calendar"
(only fordate
mode)"clock"
(only fortime
mode)
<RNDateTimePicker display="spinner" />
onChange
(optional
)
日期更改处理程序。
当用户更改 UI 中的日期或时间时调用此方法。 它接收事件和日期作为参数。
setDate = (event, date) => {}
<RNDateTimePicker onChange={this.setDate} />
value
(required
)
定义组件中使用的日期或时间值。
<RNDateTimePicker value={new Date()} />
maximumDate
(optional
)
定义可选择的最大日期。
<RNDateTimePicker maximumDate={new Date(2300, 10, 20)} />
minimumDate
(optional
)
定义可以选择的最短日期。
<RNDateTimePicker minimumDate={new Date(1950, 0, 1)} />
timeZoneOffsetInMinutes
(optional
, iOS only
)
允许更改日期选择器的时区。 默认情况下,它使用设备的时区。
// GMT+1
<RNDateTimePicker timeZoneOffsetInMinutes={60} />
locale
(optional
, iOS only
)
允许更改组件的语言环境。 默认情况下,它使用设备的区域设置。
<RNDateTimePicker locale="es-ES" />
is24Hour
(optional
, Android only
)
允许将时间选择器更改为 24 小时格式。
<RNDateTimePicker is24Hour={true} />
neutralButtonLabel
(optional
, Android only
)
允许在选择器对话框中显示中性按钮。 按下按钮可以在 onChange 处理程序中观察到 event.type === 'neutralButtonPressed'
<RNDateTimePicker neutralButtonLabel="clear" />
minuteInterval
(optional
, iOS only
)
可以选择分钟的间隔。 可能的值是:1, 2, 3, 4, 5, 6, 10, 12, 15, 20, 30
<RNDateTimePicker minuteInterval={10} />
Migration from the older components
RNDateTimePicker
是用来表示旧的新通用名称iOS 和 Android 版本。
在 Android 上,如果属性 value
发生变化,打开的选择器模式将更新所选的日期和/或时间。 例如,如果 HOC 持有状态,则更新 value
属性。 以前该组件用于关闭模态并在连续调用时呈现一个新模态。
DatePickerIOS
initialDate
已弃用,请改用value
。// Before <DatePickerIOS initialValue={new Date()} />
// Now <RNDateTimePicker value={new Date()} />
date
已弃用,请改用value
。// Before <DatePickerIOS date={new Date()} />
// Now <RNDateTimePicker value={new Date()} />
onChange
现在也返回日期。// Before onChange = (event) => {} <DatePickerIOS onChange={this.onChange} />
// Now onChange = (event, date) => {} <RNDateTimePicker onChange={this.onChange} />
onDateChange
已弃用,请改用onChange
。// Before setDate = (date) => {} <DatePickerIOS onDateChange={this.setDate} />
// Now setDate = (event, date) => {} <RNDateTimePicker onChange={this.setDate} />
DatePickerAndroid
date
已弃用,请改用value
。// Before try { const {action, year, month, day} = await DatePickerAndroid.open({ date: new Date() }); } catch ({code, message}) { console.warn('Cannot open date picker', message); }
// Now <RNDateTimePicker mode="date" value={new Date()} />
minDate
和maxDate
已弃用,请改用minimumDate
和maximumDate
。// Before try { const {action, year, month, day} = await DatePickerAndroid.open({ minDate: new Date(), maxDate: new Date() }); } catch ({code, message}) { console.warn('Cannot open date picker', message); }
// Now <RNDateTimePicker mode="date" minimumDate={new Date()} maximumDate={new Date()} />
dateSetAction
已弃用,请改用onChange
。// Before try { const {action, year, month, day} = await DatePickerAndroid.open(); if (action === DatePickerAndroid.dateSetAction) { // Selected year, month (0-11), day } } catch ({code, message}) { console.warn('Cannot open date picker', message); }
// Now setDate = (event, date) => { if (date !== undefined) { // timeSetAction } } <RNDateTimePicker mode="date" onChange={this.setDate} />
dismissedAction
已弃用,请改用onChange
。// Before try { const {action, year, month, day} = await DatePickerAndroid.open(); if (action === DatePickerAndroid.dismissedAction) { // Dismissed } } catch ({code, message}) { console.warn('Cannot open date picker', message); }
// Now setDate = (event, date) => { if (date === undefined) { // dismissedAction } } <RNDateTimePicker mode="date" onChange={this.setDate} />
TimePickerAndroid
hour
和minute
已弃用,请改用value
。// Before try { const {action, hour, minute} = await TimePickerAndroid.open({ hour: 14, minute: 0, is24Hour: false, // Will display '2 PM' }); if (action !== TimePickerAndroid.dismissedAction) { // Selected hour (0-23), minute (0-59) } } catch ({code, message}) { console.warn('Cannot open time picker', message); }
// Now // It will use the hour and minute defined in date <RNDateTimePicker mode="time" value={new Date()} />
timeSetAction
已弃用,请改用onChange
。// Before try { const {action, hour, minute} = await TimePickerAndroid.open(); if (action === TimePickerAndroid.timeSetAction) { // Selected hour (0-23), minute (0-59) } } catch ({code, message}) { console.warn('Cannot open time picker', message); }
// Now setTime = (event, date) => { if (date !== undefined) { // Use the hour and minute from the date object } } <RNDateTimePicker mode="time" onChange={this.setTime} />
dismissedAction
已弃用,请改用onChange
。// Before try { const {action, hour, minute} = await TimePickerAndroid.open(); if (action === TimePickerAndroid.dismissedAction) { // Dismissed } } catch ({code, message}) { console.warn('Cannot open time picker', message); }
// Now setTime = (event, date) => { if (date === undefined) { // dismissedAction } } <RNDateTimePicker mode="time" onChange={this.setTime} />
Contributing to the component
Manual installation
iOS
安装 CocoaPods,此处是安装指南。
在 iOS 文件夹中运行
pod init
,这将创建初始pod
文件。文件更新为如下所示(请记住将
MyApp
替换为您的目标名称):# Allowed sources source 'https://github.com/CocoaPods/Specs.git' target 'MyApp' do # As we use Swift, ensure that `use_frameworks` is enabled. use_frameworks! # Specific iOS platform we are targetting platform :ios, '8.0' # Point to the installed version pod 'RNDateTimePicker', :path => '../node_modules/@react-native-community/datetimepicker/RNDateTimePicker.podspec' # React/React-Native specific pods pod 'React', :path => '../node_modules/react-native', :subspecs => [ 'Core', 'CxxBridge', # Include this for RN >= 0.47 'DevSupport', # Include this to enable In-App Devmenu if RN >= 0.43 'RCTText', 'RCTNetwork', 'RCTWebSocket', # Needed for debugging ] # Explicitly include Yoga if you are using RN >= 0.42.0 pod 'yoga', :path => '../node_modules/react-native/ReactCommon/yoga' # Third party deps podspec link pod 'DoubleConversion', :podspec => '../node_modules/react-native/third-party-podspecs/DoubleConversion.podspec' pod 'glog', :podspec => '../node_modules/react-native/third-party-podspecs/glog.podspec' pod 'Folly', :podspec => '../node_modules/react-native/third-party-podspecs/Folly.podspec' end
将您的
pod
pod
文件已创建npm run start
npm run start:ios
Android
- Add the following lines to
android/settings.gradle
:
include ':@react-native-community_datetimepicker'
project(':@react-native-community_datetimepicker').projectDir = new File(rootProject.projectDir, '../node_modules/@react-native-community/datetimepicker/android')
- Add the compile line to the dependencies in
android/app/build.gradle
:
dependencies {
...
implementation project(':@react-native-community_datetimepicker')
}
- Add the import and link the package in
MainApplication.java
:
+ import com.reactcommunity.rndatetimepicker.RNDateTimePickerPackage;
public class MainApplication extends Application implements ReactApplication {
@Override
protected List<ReactPackage> getPackages() {
@SuppressWarnings("UnnecessaryLocalVariable")
List<ReactPackage> packages = new PackageList(this).getPackages();
// Packages that cannot be autolinked yet can be added manually here, for example:
+ packages.add(new RNDateTimePickerPackage());
return packages;
}
}
Running the example app
- Install required pods in
example/ios
by runningpods install
- Run
npm start
to start Metro Bundler - Run
npm run start:ios
ornpm run start:android
React Native DateTimePicker
React Native date & time picker component for iOS and Android
iOS | |
Android | |
Table of Contents
- React Native DateTimePicker
- Getting started
- General Usage
- Props
mode
(optional
)display
(optional
,Android only
)onChange
(optional
)value
(required
)maximumDate
(optional
)minimumDate
(optional
)timeZoneOffsetInMinutes
(optional
,iOS only
)locale
(optional
,iOS only
)is24Hour
(optional
,Android only
)neutralButtonLabel
(optional
,Android only
)minuteInterval
(optional
,iOS only
)
- Migration from the older components
- Contributing to the component
- Manual installation
- Running the example app
Getting started
npm install @react-native-community/datetimepicker --save
or
yarn add @react-native-community/datetimepicker
RN >= 0.60
If you are using RN >= 0.60, only run pod install
from the ios directory. Then rebuild your project.
RN < 0.60
For RN < 0.60, you need to link the dependency using react-native link
:
react-native link @react-native-community/datetimepicker
Then run pod install
from the ios directory and rebuild your project.
If this does not work, see Manual installation.
General Usage
import DateTimePicker from '@react-native-community/datetimepicker';
or
const DateTimePicker = require('@react-native-community/datetimepicker');
Basic usage with state
import React, {useState} from 'react';
import {View, Button, Platform} from 'react-native';
import DateTimePicker from '@react-native-community/datetimepicker';
const App = () => {
const [date, setDate] = useState(new Date(1598051730000));
const [mode, setMode] = useState('date');
const [show, setShow] = useState(false);
const onChange = (event, selectedDate) => {
const currentDate = selectedDate || date;
setDate(currentDate);
setShow(Platform.OS === 'ios' ? true : false);
};
const showMode = currentMode => {
setShow(true);
setMode(currentMode);
};
const showDatepicker = () => {
showMode('date');
};
const showTimepicker = () => {
showMode('time');
};
return (
<View>
<View>
<Button onPress={showDatepicker} title="Show date picker!" />
</View>
<View>
<Button onPress={showTimepicker} title="Show time picker!" />
</View>
{show && (
<DateTimePicker
testID="dateTimePicker"
timeZoneOffsetInMinutes={0}
value={date}
mode={mode}
is24Hour={true}
display="default"
onChange={onChange}
/>
)}
</View>
);
};
export default App;
Props
Please note that this library currently exposes functionality from
UIDatePicker
on iOS and DatePickerDialog + TimePickerDialog on Android.These native classes offer only limited configuration, while there are dozens of possible options you as a developer may need. It follows that if your requirement is not supported by the backing native views, this libray will not be able to implement your requirement. When you open an issue with a feature request, please document if (or how) the feature can be implemented using the aforementioned native views. If those views do not support what you need, such feature requests will be closed as not actionable.
mode
(optional
)
Defines the type of the picker.
List of possible values:
"date"
(default foriOS
andAndroid
)"time"
"datetime"
(iOS
only)"countdown"
(iOS
only)
<RNDateTimePicker mode="time" />
display
(optional
, Android only
)
Defines the visual display of the picker for Android and will be ignored for iOS.
List of possible values:
"default"
"spinner"
"calendar"
(only fordate
mode)"clock"
(only fortime
mode)
<RNDateTimePicker display="spinner" />
onChange
(optional
)
Date change handler.
This is called when the user changes the date or time in the UI. It receives the event and the date as parameters.
setDate = (event, date) => {}
<RNDateTimePicker onChange={this.setDate} />
value
(required
)
Defines the date or time value used in the component.
<RNDateTimePicker value={new Date()} />
maximumDate
(optional
)
Defines the maximum date that can be selected.
<RNDateTimePicker maximumDate={new Date(2300, 10, 20)} />
minimumDate
(optional
)
Defines the minimum date that can be selected.
<RNDateTimePicker minimumDate={new Date(1950, 0, 1)} />
timeZoneOffsetInMinutes
(optional
, iOS only
)
Allows changing of the timeZone of the date picker. By default it uses the device's time zone.
// GMT+1
<RNDateTimePicker timeZoneOffsetInMinutes={60} />
locale
(optional
, iOS only
)
Allows changing of the locale of the component. By default it uses the device's locale.
<RNDateTimePicker locale="es-ES" />
is24Hour
(optional
, Android only
)
Allows changing of the time picker to a 24 hour format.
<RNDateTimePicker is24Hour={true} />
neutralButtonLabel
(optional
, Android only
)
Allows displaying neutral button on picker dialog. Pressing button can be observed in onChange handler as event.type === 'neutralButtonPressed'
<RNDateTimePicker neutralButtonLabel="clear" />
minuteInterval
(optional
, iOS only
)
The interval at which minutes can be selected. Possible values are: 1, 2, 3, 4, 5, 6, 10, 12, 15, 20, 30
<RNDateTimePicker minuteInterval={10} />
Migration from the older components
RNDateTimePicker
is the new common name used to represent the old versions of iOS and Android.
On Android, open picker modals will update the selected date and/or time if the prop value
changes. For example, if a HOC holding state, updates the value
prop. Previously the component used to close the modal and render a new one on consecutive calls.
DatePickerIOS
initialDate
is deprecated, usevalue
instead.// Before <DatePickerIOS initialValue={new Date()} />
// Now <RNDateTimePicker value={new Date()} />
date
is deprecated, usevalue
instead.// Before <DatePickerIOS date={new Date()} />
// Now <RNDateTimePicker value={new Date()} />
onChange
now returns also the date.// Before onChange = (event) => {} <DatePickerIOS onChange={this.onChange} />
// Now onChange = (event, date) => {} <RNDateTimePicker onChange={this.onChange} />
onDateChange
is deprecated, useonChange
instead.// Before setDate = (date) => {} <DatePickerIOS onDateChange={this.setDate} />
// Now setDate = (event, date) => {} <RNDateTimePicker onChange={this.setDate} />
DatePickerAndroid
date
is deprecated, usevalue
instead.// Before try { const {action, year, month, day} = await DatePickerAndroid.open({ date: new Date() }); } catch ({code, message}) { console.warn('Cannot open date picker', message); }
// Now <RNDateTimePicker mode="date" value={new Date()} />
minDate
andmaxDate
are deprecated, useminimumDate
andmaximumDate
instead.// Before try { const {action, year, month, day} = await DatePickerAndroid.open({ minDate: new Date(), maxDate: new Date() }); } catch ({code, message}) { console.warn('Cannot open date picker', message); }
// Now <RNDateTimePicker mode="date" minimumDate={new Date()} maximumDate={new Date()} />
dateSetAction
is deprecated, useonChange
instead.// Before try { const {action, year, month, day} = await DatePickerAndroid.open(); if (action === DatePickerAndroid.dateSetAction) { // Selected year, month (0-11), day } } catch ({code, message}) { console.warn('Cannot open date picker', message); }
// Now setDate = (event, date) => { if (date !== undefined) { // timeSetAction } } <RNDateTimePicker mode="date" onChange={this.setDate} />
dismissedAction
is deprecated, useonChange
instead.// Before try { const {action, year, month, day} = await DatePickerAndroid.open(); if (action === DatePickerAndroid.dismissedAction) { // Dismissed } } catch ({code, message}) { console.warn('Cannot open date picker', message); }
// Now setDate = (event, date) => { if (date === undefined) { // dismissedAction } } <RNDateTimePicker mode="date" onChange={this.setDate} />
TimePickerAndroid
hour
andminute
are deprecated, usevalue
instead.// Before try { const {action, hour, minute} = await TimePickerAndroid.open({ hour: 14, minute: 0, is24Hour: false, // Will display '2 PM' }); if (action !== TimePickerAndroid.dismissedAction) { // Selected hour (0-23), minute (0-59) } } catch ({code, message}) { console.warn('Cannot open time picker', message); }
// Now // It will use the hour and minute defined in date <RNDateTimePicker mode="time" value={new Date()} />
timeSetAction
is deprecated, useonChange
instead.// Before try { const {action, hour, minute} = await TimePickerAndroid.open(); if (action === TimePickerAndroid.timeSetAction) { // Selected hour (0-23), minute (0-59) } } catch ({code, message}) { console.warn('Cannot open time picker', message); }
// Now setTime = (event, date) => { if (date !== undefined) { // Use the hour and minute from the date object } } <RNDateTimePicker mode="time" onChange={this.setTime} />
dismissedAction
is deprecated, useonChange
instead.// Before try { const {action, hour, minute} = await TimePickerAndroid.open(); if (action === TimePickerAndroid.dismissedAction) { // Dismissed } } catch ({code, message}) { console.warn('Cannot open time picker', message); }
// Now setTime = (event, date) => { if (date === undefined) { // dismissedAction } } <RNDateTimePicker mode="time" onChange={this.setTime} />
Contributing to the component
Please see CONTRIBUTING.md
Manual installation
iOS
Install CocoaPods, here the installation guide.
Inside the iOS folder run
pod init
, this will create the initialpod
file.Update your
pod
file to look like the following ( Remember to replaceMyApp
with your target name ):# Allowed sources source 'https://github.com/CocoaPods/Specs.git' target 'MyApp' do # As we use Swift, ensure that `use_frameworks` is enabled. use_frameworks! # Specific iOS platform we are targetting platform :ios, '8.0' # Point to the installed version pod 'RNDateTimePicker', :path => '../node_modules/@react-native-community/datetimepicker/RNDateTimePicker.podspec' # React/React-Native specific pods pod 'React', :path => '../node_modules/react-native', :subspecs => [ 'Core', 'CxxBridge', # Include this for RN >= 0.47 'DevSupport', # Include this to enable In-App Devmenu if RN >= 0.43 'RCTText', 'RCTNetwork', 'RCTWebSocket', # Needed for debugging ] # Explicitly include Yoga if you are using RN >= 0.42.0 pod 'yoga', :path => '../node_modules/react-native/ReactCommon/yoga' # Third party deps podspec link pod 'DoubleConversion', :podspec => '../node_modules/react-native/third-party-podspecs/DoubleConversion.podspec' pod 'glog', :podspec => '../node_modules/react-native/third-party-podspecs/glog.podspec' pod 'Folly', :podspec => '../node_modules/react-native/third-party-podspecs/Folly.podspec' end
Run
pod install
inside the same folder where thepod
file was creatednpm run start
npm run start:ios
Android
- Add the following lines to
android/settings.gradle
:
include ':@react-native-community_datetimepicker'
project(':@react-native-community_datetimepicker').projectDir = new File(rootProject.projectDir, '../node_modules/@react-native-community/datetimepicker/android')
- Add the compile line to the dependencies in
android/app/build.gradle
:
dependencies {
...
implementation project(':@react-native-community_datetimepicker')
}
- Add the import and link the package in
MainApplication.java
:
+ import com.reactcommunity.rndatetimepicker.RNDateTimePickerPackage;
public class MainApplication extends Application implements ReactApplication {
@Override
protected List<ReactPackage> getPackages() {
@SuppressWarnings("UnnecessaryLocalVariable")
List<ReactPackage> packages = new PackageList(this).getPackages();
// Packages that cannot be autolinked yet can be added manually here, for example:
+ packages.add(new RNDateTimePickerPackage());
return packages;
}
}
Running the example app
- Install required pods in
example/ios
by runningpods install
- Run
npm start
to start Metro Bundler - Run
npm run start:ios
ornpm run start:android