2017-08-28 10 views
0

私は次の日(nextDay)である日付をマークしたいCalenderコンポーネントを持っています。私は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月16日」のようで行うのでマーク定数をnextDay(すなわち、2017年8月29日)のデータを使用できますか?

私はこの方法を試みた:

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

をしかし、その代わりにtoday(即ち、2017年8月29日)の値を使用することは、キーの名前としてtoday自体を使用します。

+2

使用ブラケット表記、このようにそれを書く: 'constのマーク= { [nextDay]:{選択済み: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);

関連する問題