【发布时间】:2020-10-21 00:40:15
【问题描述】:
我正在使用 React 前端进行编码,在寻找一种在日历上选择日期的方法时,我遇到了一个很酷的 React 模块,名为 "react-datepicker"。这几乎可以满足我的所有需求。我正在尝试使用指南网站上看到的<DatePicker /> 组件:https://reactdatepicker.com/
我遇到的问题是钩子调用。我似乎找不到这个钩子调用的解决方法。当用户在日历上选择一个日期时,选择的日期将作为文本输入中的值放置。完成此操作的方法是使用网站上的钩子调用。
现在这是我的问题。我希望能够使用我已经编写的onChange 函数(如果可能的话)来改变当前网页上的内容。似乎在render() 函数调用之外的函数中存在挂钩调用的问题,因为当我尝试在onChange 函数内部调用挂钩时出现错误:Uncaught Error: Invalid hook call. Hooks can only be called inside of the body of a function component...。是否有解决方法来更改 DataPicker 文本输入的文本输入值?这是我现在最好的尝试:
import React, { Component, useState } from "react";
...
import DatePicker from 'react-datepicker';
...
export class AddEvent extends Component {
...
onChange = (handleChange) => (e, e2) => {
if (e2 == null && e != null) {
this.setState({ [e.target.name]: e.target.value });
} else if (e2 === null && e === null) {
//The value I really want to show up in the text box is the one set here
//It can be accessed for this example as this.state.days[0]
this.setState({ ...this.state, "days": [null]});
handleChange();
} else {
...
if ... {
...
} else{
//The value I really want to show up in the text box is the one set here
//It can be accessed for this example as this.state.days[0]
this.setState({ ...this.state, "days": [e] });
handleChange();
}
}
}
render() {
//The value I really want to show up in the text box is the one in this.state.days[0]
const minDate = new Date();
const [aDate, setDate] = useState(minDate);
const handleChange = date => setDate(date);
return(
<div className="mt-4 mb-4">
<form onSubmit={this.onSubmit}>
...
<div>
<label>Choose the Day(s) the Event could/will occur on:</label>
<DatePicker name="day1" onChange={this.onChange(handleChange)} minDate = {minDate} dateFormat="mm/dd/yyyy" />
</div>
...
</form>
</div>
);
}
}
...
【问题讨论】:
-
React hooks 仅在功能组件或自定义 react hooks 中有效,不能在基于类的组件中使用。只需创建正常的组件状态并使用生命周期方法对其进行更新,或者将您的组件转换为功能组件。
标签: javascript reactjs datepicker react-datepicker