javascript - React can't null datetime-local input field
问题描述
I'm using react together with react-semantic-ui and I'm having following input type:
<Input
onChange={e => this.onTextInputChange(e, 'date')}
value={this.state.searchQuery.date}
type='datetime-local'/>
onTextInputChange
function sets input value as the state field and value of this input is bound to this field. Also, I have an additional button in my app which is responsible for clear form fields (by setting null on each state field).
state = {
searchQuery: {
date: null
}
}
Clear works pretty well for other fields, but the problem occurs when I touch datetime-local
input. When I fill some part of the date I'm getting this message when I hit the clear button.
I'm able to clear this field only when I provide a full date. I know I can solve this issue by setting the value of this field to blank string ' '
during clear, but it isn't the best solution, because later I have to filter out those fields. I was even playing with react ref, but unfortunately I didn't achieve any positive result, what's more, blue cross which appears on hover clears the form. Any tips how can I handle it in a pretty way?
Edit #1:
event.preventDefault
helped me to get rid of this validation message, but anyway input stays without cleared value.
解决方案
不知何故,我找到了处理它的方法。
我Ref
在构造函数中做了:
...
dateRef: any;
constructor(props: Readonly<Properties>) {
super(props);
this.dateRef = React.createRef();
}
...
将 ref 分配给我的输入:
<Input
...
type='datetime-local'/
ref={this.dateRef}
...
/>
在 clearForm 方法中,我''
在 UI 和状态中设置了 null 值。
private clearForm = (event: React.FormEvent): void => {
event.preventDefault();
this.date.current.inputRef.current.value = '';
this.setState({searchQuery: EMPTY_SEARCH_QUERY});
}
此外,如果通过访问输入无效,我也会阻止搜索this.dateRef.current.inputRef.current.validity.valid
也许这个解决方案不是最好的,但它确实有效。
推荐阅读
- amazon-web-services - 在 dynamoDB 中获取日期范围的数据
- java - 检查索引处的特定值时出错为空
- docker - 在 Synology NAS 上授予访问 /var/run/docker.sock 的权限
- php - 将分钟添加到日期时间无法正常工作
- sql - 对于所有正在运行的查询,在 Oracle SQL Developer 中查找特定用户/机器的活动查询的当前查询时间的最佳方法是什么?
- python - 按多个子属性对父模型排序 SQLAlchemy
- regex - 正则表达式忽略行项目编号和金额之间的所有字符
- javascript - Visual Studio Code 2020 - git 连接和添加项目
- c++ - 将 auto 与虚函数一起使用……如何让这段代码运行?
- ios - 在 iPhone 文件中将 UIimage(照片库或相机)转换为 PDF