[英]Manipulating dates Momentjs in ReactJS
I have a basic ES6 react app and am trying to use momentJS to manipulate some dates. 我有一个基本的ES6 react应用,正在尝试使用momentJS处理一些日期。 For some reason I keep getting
month.add is not a function
由于某些原因,我不断获得
month.add is not a function
Currently the code I have is this: 目前我拥有的代码是这样的:
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>
)
}
} }
I have tried various versions of setting the initial state using Moment().month()
etc but nothing seems to work. 我已经尝试过使用
Moment().month()
等设置初始状态的各种版本,但似乎没有任何效果。 Any help would be much appreciated. 任何帮助将非常感激。
When you do .format()
you are turning it into a string, it's no longer a momentJS object. 当您执行
.format()
时,将其转换为字符串,它不再是momentJS对象。
moment().add(1, 'months') // A moment object
moment().add(1, 'months').subtract(6, 'days') // Can still manipulate
moment().add(1, 'months').subtract(6, 'days').format() // A final string, can't call moment funcs on it
Also there's no need to create multiple objects if they're all using the same time - 同样,如果它们都使用同一时间,则无需创建多个对象-
const momentNow = Moment();
this.state = {
currentDate: momentNow.format(),
month: momentNow.format('MMMM'),
year: momentNow.format('YYYY')
}
Your state.month is a string. 您的state.month是一个字符串。 That's causing the issue.
这就是问题所在。
Try this 尝试这个
constructor() {
super();
this.state = {
currentDate: Moment(),
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 date = this.state.currentDate;
date.add(-1, 'months');
this.setState({
currentDate: date,
month: date.format('MMMM'),
year: date.format('YYYY')
});
}
nextMonth() {
let date = this.state.currentDate;
date.add(1, 'months');
this.setState({
currentDate: date,
month: date.format('MMMM'),
year: date.format('YYYY')
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.