在 React Native 日历中突出显示按下(选定)的日期

Jas*_*nov 5 javascript highlight reactjs 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});
};
Run Code Online (Sandbox Code Playgroud)

SDu*_*han 9

根据您需要使用的文档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}
  }}
/>
Run Code Online (Sandbox Code Playgroud)

编辑

  1. 添加markedDates到初始状态。
state = {
    selectedDate: "",
    markedDates: {}
};
Run Code Online (Sandbox Code Playgroud)
  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
    });
};
Run Code Online (Sandbox Code Playgroud)
  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);
  }}
/>

Run Code Online (Sandbox Code Playgroud)

如果您有任何面团,请随时询问。希望这会对您有所帮助。