我对 React 还很陌生,我正在使用一个简单的 create-react-app 来显示使用 React-calendar-pane ( https://github.com/tomkp/react-calendar-pane ) 的日历。我正在尝试做一些事情,当用户在日历中选择日期时,该日期会显示在日历上方。我的 App.js 文件中有以下内容:
import Calendar from 'react-calendar-pane';
import moment, { calendarFormat } from 'moment';
import date from 'react-calendar-pane';
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h1 className="App-title">Welcome to React</h1>
</header>
<p> The date you've selected is: this.props.onClick{date}</p>
<Calendar date={moment("23/10/2015", "DD/MM/YYYY")} onSelect={this.onSelect} />
</div>
我通过尝试了解react-calendar-pane组件得出了这个结论,但它根本无法处理诸如“警告:失败的 Prop 类型: Prop onSelect
被标记为必需”之类的错误在Calendar
中,但其值为undefined
。
在日历中(位于 App.js:20)
在应用程序中(位于index.js:7)”
我觉得我正在以一种稍微错误的方式处理它,所以任何建议或解决方案都将非常感激。谢谢。
最佳答案
您收到您提到的错误,因为您尚未定义 this.onSelect
。 Calendar
需要onSelect
支柱;这样当您选择日期时,它可以将其传递回 onSelect
功能。您还没有写入 onSelect
的内容函数,因此它是 undefined
。这就是您收到该错误的原因。
因此,要做的第一件事就是写 onSelect
功能。 Calendar
将调用 onSelect
每当选择日期时,它都会将日期值传递回该函数。如果你写onSelect
功能如下:
onSelect=(e)=>{
console.log(e);
}
并将其传递给Calendar
正如您所做的那样,您可以在 console
中看到每当您单击某个日期时,该日期都会显示为 moment
对象。
现在,由于我们必须显示日期,因此我们可以将其存储在 state
中。我们将其保存在我们的状态中,以便每当我们单击另一个日期时 state
将会改变,我们显示的日期也会改变。
因此创建一个状态对象:
constructor(){
super();
this.state={
selectedDate:moment(),
}
}
我们已经初始化了selectedDate
与 moment()
。这样,如果未选择日期,它将显示今天的日期。
现在我们更改 onSelect
函数为
onSelect=(e)=>{
this.setState({selectedDate:e})
}
每当我们单击Calendar
中的日期时,这会将日期设置为所选日期。 .
现在要显示日期,您必须更改
<p> The date you've selected is: this.props.onClick{date}</p>
到
<p> The date you've selected is: {this.state.selectedDate.format('YYYY-MM-DD')} </p>
这将显示this.date.selectedDate
。 format
就是将对象转换为指定格式的字符串。
现在最终的代码应该如下所示
import React from 'react'
import Calendar from 'react-calendar-pane';
import moment, { calendarFormat } from 'moment';
import date from 'react-calendar-pane';
class StackOverflow extends React.Component {
constructor(){
super();
this.state={
selectedDate:moment(),
}
}
onSelect=(e)=>{
this.setState({selectedDate:e})
}
render () {
return(
<div>
<div className="App">
<header className="App-header">
<h1 className="App-title">Welcome to React</h1>
</header>
<p> The date you've selected is: {this.state.selectedDate.format('YYYY-MM-DD')} </p>
<Calendar date={moment("23/10/2015", "DD/MM/YYYY")} onSelect={this.onSelect} />
</div>
</div>
)
}
}
export default StackOverflow;
关于javascript - 如何使用react-calendar-pane显示日历中选定的日期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49793031/