如何在React Native的react-native-calendars中动态标记多个日期?
解决react-native-calendars动态标记多个日期的问题
嘿,我知道你在用react-native-calendars的Calendar组件时,尝试标记多个日期却没成功,问题出在你构建markedDates对象的方式上,我来帮你搞定~
问题所在
你之前的代码里,直接把整个日期数组作为对象的键:
const mark = { [nextDay]: {selected: true, marked: true} };
这会把数组转成一个逗号分隔的字符串(比如"2018-06-01,2018-06-05,..."),根本不是组件能识别的单个日期格式,所以自然无法标记任何日期。
正确的实现方式
react-native-calendars要求markedDates是一个以单个日期字符串为键的对象,每个键对应该日期的标记配置。我们可以通过遍历日期数组,用reduce方法构建符合要求的对象:
步骤1:构建正确的markedDates对象
// 你的日期数组 const nextDay = ['2018-06-01', '2018-06-05', '2018-06-08', '2018-06-07', '2018-06-18', '2018-06-17', '2018-05-28', '2018-05-29']; // 遍历数组,生成符合要求的markedDates const markedDates = nextDay.reduce((acc, date) => { // 给每个日期设置标记属性 acc[date] = { selected: true, marked: true }; return acc; }, {});
这样生成的markedDates结构会是:
{ "2018-06-01": { selected: true, marked: true }, "2018-06-05": { selected: true, marked: true }, // ...其他日期 }
这正是组件需要的格式。
步骤2:完整的组件示例
import React, { Component } from 'react'; import { Calendar } from 'react-native-calendars'; class CustomCalendar extends Component { constructor(props) { super(props); const nextDay = ['2018-06-01', '2018-06-05', '2018-06-08', '2018-06-07', '2018-06-18', '2018-06-17', '2018-05-28', '2018-05-29']; // 初始化时构建markedDates const markedDates = nextDay.reduce((acc, date) => { acc[date] = { selected: true, marked: true }; return acc; }, {}); this.state = { markedDates }; } onDayPress = (day) => { // 这里可以添加日期点击的逻辑 console.log('Pressed day:', day); }; render() { return ( <Calendar onDayPress={this.onDayPress} current={new Date()} minDate={'2018-05-24'} onMonthChange={(month) => {console.log('month changed', month)}} hideArrows={false} hideExtraDays={true} disableMonthChange={false} firstDay={1} hideDayNames={false} showWeekNumbers={false} onPressArrowLeft={substractMonth => substractMonth()} onPressArrowRight={addMonth => addMonth()} markedDates={this.state.markedDates} theme={{ backgroundColor: '#ffffff', calendarBackground: '#ffffff', textSectionTitleColor: '#b6c1cd', selectedDayBackgroundColor: '#00adf5', selectedDayTextColor: '#ffffff', todayTextColor: '#00adf5', dayTextColor: '#2d4150', textDisabledColor: '#d9e1e8', dotColor: '#00adf5', selectedDotColor: '#ffffff', arrowColor: 'orange', monthTextColor: 'blue', textMonthFontWeight: 'bold', textDayFontSize: 16, textMonthFontSize: 16, textDayHeaderFontSize: 16 }} /> ); } } export default CustomCalendar;
额外注意事项
- 确保日期格式严格是
YYYY-MM-DD,和组件要求一致; - 如果是动态获取日期(比如从接口请求),在拿到数据后重新构建
markedDates并调用this.setState更新状态即可; - 你之前写的
this.state({ mark: mark, })是错误的,初始化state要在constructor里用this.state = {...},更新状态要用this.setState()。
内容的提问来源于stack exchange,提问作者devedv
相关产品推荐
相关产品推荐

