我有一个基本的ES6反应的应用程序,并试图用momentJS来操纵一些日期。出于某种原因,我不断收到month.add is not a function
操作日期Momentjs在ReactJS
目前我的代码是这样的:
export default class CalendarApp extends React.Component {
constructor() {
super();
this.state = {
currentDate: Moment().format(),
month: Moment().format('MMMM'),
year: Moment().format('YYYY')
}
// Bind Methods to this
this.previousMonth = this.previousMonth.bind(this);
this.nextMonth = this.nextMonth.bind(this);
}
previousMonth() {
let month = this.state.month;
month.add(-1, 'months');
this.setState({
month: month
})
}
nextMonth() {
let month = this.state.month;
month.add(1, 'months');
this.setState({
month: month
})
}
render() {
return (
<div className="calendar">
<div className="calendar-container" style={ hideCalendar }>
<caption>
<button className="previous-month" onClick={ this.previousMonth }>Prev</button>
<button className="next-month" onClick={ this.nextMonth }>Next</button>
<div className="calendar-month">
<span>{ this.state.month } { this.state.year }</span>
</div>
</caption>
</div>
</div>
)
}
}
我曾尝试使用Moment().month()
等,但似乎没有任何工作设置的初始状态的各种版本。任何帮助将非常感激。
感谢您的答复。如果我只在状态中创建1个对象,例如currentDate,那么稍后可以使用'this.state.currentDate.format(“MMMM”)'? –
是的,这是可能的。你只需更新html。 –
是的,你可以,虽然目前的时间可能是在创建对象的时候,而不是当你做一个.format的时候 - 可能不是一个问题,但值得铭记 –