You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在react-native-calendars中调整时间间隔至15分钟

解决react-native-calendars TimelineList自定义时间间隔的问题

react-native-calendars的Timeline组件没有直接提供修改时间间隔的配置项,但可以通过自定义时间标签渲染 + 调整时间线高度刻度的组合方式,实现15分钟或任意自定义时长的时间间隔需求。

具体实现步骤

1. 自定义时间标签渲染

在timelineProps中添加renderTimeLabel方法,生成指定间隔的时间标签(以15分钟为例):

// 生成15分钟间隔的时间标签
const renderTimeLabel = (date) => {
  const hours = date.getHours().toString().padStart(2, '0');
  const minutes = date.getMinutes().toString().padStart(2, '0');
  // 仅显示整点、15分、30分、45分的标签
  if (['00', '15', '30', '45'].includes(minutes)) {
    return <Text style={{ fontSize: 12, color: '#666' }}>{`${hours}:${minutes}`}</Text>;
  }
  // 不需要显示的间隔返回空视图
  return null;
};

2. 调整时间线高度刻度

默认timelineHourHeight(主题配置)为60,对应1小时的高度(30分钟占30高度)。要适配15分钟间隔,需将timelineHourHeight设为120,让1小时被拆分为4个15分钟刻度:

const customTheme = {
  // 保留你的其他主题配置
  timelineHourHeight: 120, // 1小时高度设为120,每个15分钟刻度对应30高度
};

3. 事件高度适配(可选)

事件高度默认会根据timelineHourHeight自动计算,若你的事件时长精确到15分钟,无需额外调整。若有特殊需求,可在renderEvent中手动计算:

const renderEvent = (event) => {
  // 按15分钟刻度计算事件高度:时长分钟数 /15 * 30
  const eventHeight = (event.duration / 15) * 30;
  return (
    <View style={{ height: eventHeight, backgroundColor: event.color, borderRadius: 4, padding: 4 }}>
      <Text style={{ color: 'white', fontSize: 12 }}>{event.title}</Text>
    </View>
  );
};

4. 整合到现有代码

修改后的完整代码示例:

<CalendarProvider  
  date={dayPressed ?? DateTime.now().toISODate()}
  onDateChanged={(date) => { setDayPressed(date) }}
>
  <ExpandableCalendar
    firstDay={1}
    onDayPress={(day) => { setDayPressed(day.dateString); }}
  />
  <TimelineList
    timelineProps={{
      start: startHour,
      end: endHour,
      unavailableHoursColor: "rgb(235, 235, 235)",
      onBackgroundLongPress: handleBackgroundLongPress,
      onEventPress(event) {
        openEventModal(event);
      },
      renderEvent: renderEvent, 
      theme: customTheme,
      // 加入自定义时间标签渲染方法
      renderTimeLabel: renderTimeLabel,
    }}
    events={events}
    showNowIndicator
    scrollToFirst
    initialTime={INITIAL_TIME}
  />
</CalendarProvider>

扩展说明

  • 若需要其他间隔(如10分钟),只需修改renderTimeLabel的判断条件,并调整timelineHourHeight(例如设为180,让1小时拆分为6个10分钟刻度)。
  • 确保start和end参数覆盖你需要展示的时间范围(如start=8表示从8点开始)。

内容的提问来源于stack exchange,提问作者Victor Vasilev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 06:03:23