首页 > 解决方案 > 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.

enter image description here

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.

标签: javascriptreactjssemantic-uisemantic-ui-react

解决方案


不知何故,我找到了处理它的方法。

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

也许这个解决方案不是最好的,但它确实有效。


推荐阅读