2017-08-28 82 views
0

我有一個日曆組件,我要標記第二天(nextDay)的日期。我正在使用react-native-calendars如何使用變量的值作爲關鍵值對的關鍵名稱

export default class CustomCalender extends React.Component { 
    render() { 
     const today = moment().format("YYYY-MM-DD"); 
     const nextDay = moment().add(1, 'days').format("YYYY-MM-DD"); // 2017-08-29 

     const mark = { 
      '2017-08-16': {selected: true, marked: true} 
     }; 

     return (
      <View style={styles.container}> 
       <Text style={styles.labelText}>Select a date</Text> 
       <Calendar 
        minDate={today} 
        onDayPress={(day) => { 
         console.log('selected day', day) 
        }} 

        markedDates={mark} 
       /> 
      </View> 
     ) 
    } 
} 

如何使用(即2017年8月29日)的nextDay數據爲標誌不變,而不是做這樣的「2017年8月16日」的?

我試着這樣說:

const mark = { 
    today: {selected: true, marked: true} 
}; 

但不是使用的today值(即2017年8月29日),它使用today本身作爲鍵的名稱。

+2

使用括號標記,它這樣寫:'常量標誌= { [nextDay]:{selected:true,marked:true} };' –

+0

[在JavaScript對象文本中爲鍵使用變量]的可能重複(https://stackoverflow.com/questions/2274242/using-a-variable-for-a-key-in-a-javascript-object-literal ) –

回答

0

首先將標記定義爲空對象。然後分配它。

const today = moment().format("YYYY-MM-DD"); 
const mark = {}; 
mark[today] = {selected: true, marked: true}; 

Rereference:JavaScript set object key by variable

0

一個簡單的例子可以幫助你理解它好得多:

let foo = 'hello'; 
 
let bar = {}; 
 

 
//using the value stored inside foo as a key for the object 
 
bar[foo] = 'world'; 
 
console.log(bar); 
 

 
//using 'foo' directly as a key instead of the value it stored 
 
bar = { 
 
    foo: 'world' 
 
} 
 
console.log(bar);

相關問題