首页 > 解决方案 > 在 React Native 日历中突出显示按下(选定)的日期

问题描述

在我拥有的项目中,我使用了 react-native-calendars 库。目前,我可以通过 onPress 获取日期。但问题是如何突出该日期。逻辑:当用户按下日期时,它应该以任何颜色突出显示。主要原因是将所选日期与其余日期区分开来。这是源代码

这是我的代码片段,负责获取当前日期:

state={
  selectedDate: '',
}

const getSelectedDayEvents = (date) => {
    let serviceDate = moment(date);
    serviceDate = serviceDate.format("DD.MM.YYYY");
    this.setState({selectedDate: serviceDate});
};

标签: javascriptreactjsreact-nativehighlight

解决方案


根据您需要使用的文件markedDates={}来显示突出显示的日期。

<Calendar
  markedDates={{
    '2012-05-16': {selected: true, marked: true, selectedColor: 'blue'},
    '2012-05-17': {marked: true},
    '2012-05-18': {marked: true, dotColor: 'red', activeOpacity: 0},
    '2012-05-19': {disabled: true, disableTouchEvent: true}
  }}
/>

编辑

  1. 添加markedDates到初始状态。
state = {
    selectedDate: "",
    markedDates: {}
};
  1. 更改getSelectedDayEvents函数以创建markedDates对象并将其分配给状态。
getSelectedDayEvents = date => {
    let markedDates = {};
    markedDates[date] = { selected: true, color: '#00B0BF', textColor: '#FFFFFF' };
    let serviceDate = moment(date);
    serviceDate = serviceDate.format("DD.MM.YYYY");
    this.setState({
        selectedDate: serviceDate,
        markedDates: markedDates
    });
};
  1. 更改日历组件以接受markedDates
<Calendar
  style={{ height: 300, width: "90%", justifyContent: "center" }}
  theme={{
    backgroundColor: "#ffffff",
    calendarBackground: "#ffffff",
    todayTextColor: "#57B9BB",
    dayTextColor: "#222222",
    textDisabledColor: "#d9e1e8",
    monthTextColor: "#57B9BB",
    arrowColor: "#57B9BB",
    textDayFontWeight: "300",
    textMonthFontWeight: "bold",
    textDayHeaderFontWeight: "500",
    textDayFontSize: 16,
    textMonthFontSize: 18,
    selectedDayBackgroundColor: "#57B9BB",
    selectedDayTextColor: "white",
    textDayHeaderFontSize: 8
  }}
  minDate={"1996-05-10"}
  maxDate={"2030-05-30"}
  monthFormat={"MMMM yyyy "}
  markedDates={this.state.markedDates}
  scrollEnabled={true}
  horizontal={true}
  showScrollIndicator={true}
  disableMonthChange={true}
  onDayPress={day => {
    getSelectedDayEvents(day.dateString);
  }}
/>

如果你有任何面团随时问。希望这会帮助你。


推荐阅读