如何在React Native Calendars中动态填充markedDates对象?

时间:2019-04-16 21:02:35

标签: sqlite react-native object react-native-calendars

基于React-Native-Calendars文档,以下是带有硬编码markDate的测试代码,这些代码显示日历上的点:

const FirstDot = { key: 'First', color: 'blue' };
const SecondDot = { key: 'Second', color: 'blue' };

<Calendar
   current={new Date()}
   markingType={'multi-dot'}
   markedDates={{
      '2019-04-15': { dots: [FirstDot, SecondDot] },
      '2019-04-14': { dots: [FirstDot] },
   }}
/>

基本上我想根据数据显示一个或两个点。假设我要从SQLite检索数据,如何在React Native中动态填充markedDates?

this.state = { markedDates: {} };  //how to declare the state object?
//other codes.....

db.transaction((tx) => { 
    let objMarkedDates = this.state.markedDates;
    tx.executeSql('SELECT myDates, dataDots FROM myTable', 
    [], (tx, results) => {
        const len = results.rows.length;
        if (len > 0) {
            for (let i = 0; i < len; ++i) {
                if (results.rows.item(i).dataDots === 2) { //show 2 dots
                    //How to populate the date and the dots to the object???
                }
            }
        }
    }); 

    this.setState({ markedDates: objMarkedDates });
});

<Calendar
   current={new Date()}
   markingType={'multi-dot'}
   markedDates={this.state.markedDates}
/>

2 个答案:

答案 0 :(得分:0)

假设您的数据为数组形式,这就是我为json数据数组编写的内容

            var element = {};

            for(var i =0;i<this.state.array.length;i++){
                if((Object.keys(element)).indexOf(this.state.array[i].date) > -1){
                  for(var j = 0;j<Object.keys(element).length;j++){
                    if(this.state.array[i].start_date === Object.keys(element)[j]){
                      var a ={key:this.state.array[i].id,color:'red'}
                      element[this.state.array[i].date].dots.push(a);
                    }
                  }
                }else{
                  var a = {dots:[{key:this.state.array[i].id,color:'red'}]}
                  element[this.state.array[i].date+''] = a;
                }
            }

答案 1 :(得分:0)

基于以上答案

const MARKED_DATE_CONTAINER: ViewStyle = {
    backgroundColor: AppColors.primary,
    borderRadius: 0
}

const MARKED_DATE_TEXT: TextStyle = {
    color: AppColors.white
}
[![enter image description here][1]][1]```

    const customStyles = {
        container: {...MARKED_DATE_CONTAINER},
        text: {...MARKED_DATE_TEXT}
    }

var element = {};

    for(var i =0;i<array.length;i++){
        var a = {customStyles: {...customStyles}}
        element[`${formatMyDate(array[i].startDate)}`] = a;
    }


[![RESULT][1]][1]


  [1]: https://i.stack.imgur.com/1FUV7.png