gpt4 book ai didi

javascript - 在 ReactJS 中操作 Momentjs 日期

转载 作者:行者123 更新时间:2023-11-28 15:08:24 24 4
gpt4 key购买 nike

我有一个基本的 ES6 React 应用程序,并尝试使用 momentJS 来操作一些日期。由于某种原因,我不断收到 month.add is not a function

目前我的代码是这样的:

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() 等设置初始状态的各种版本,但似乎没有任何效果。任何帮助将不胜感激。

最佳答案

当你执行 .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

此外,如果多个对象都使用相同的时间,则无需创建它们 -

const momentNow = Moment();

this.state = {
currentDate: momentNow.format(),
month: momentNow.format('MMMM'),
year: momentNow.format('YYYY')
}

关于javascript - 在 ReactJS 中操作 Momentjs 日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37840978/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com