Solved: React-day-picker Daypicker Input loses focus when using custom input component

岁酱吖の 提交于 2021-01-29 08:42:21

问题


The working sandbox is https://codesandbox.io/s/react-day-picker-base-h9fv6

I have been trying to implement a simple day picker input, where you can both enter the date in the input field and select in the picker.

The problem is that when I use a custom input, <DayPickerInput component ={CustomInput}.../>, the input loses focus when the picker is used. This does not happen without a custom input. In the docs it says

"If you want to keep the focus when the user picks a day, the component class must have a focus method."

However I am not sure how I should implement this.


回答1:


If you need a custom component with a focus method, I think you need to use a class component, and refs:

class Input extends React.Component {
  constructor(props) {
    super(props);
    this.inputRef = React.createRef();
  }

  focus() {
    this.inputRef.current.focus();
  }

  render() {
    return <input {...this.props} ref={this.inputRef}/>
  }
}


来源:https://stackoverflow.com/questions/58113869/solved-react-day-picker-daypicker-input-loses-focus-when-using-custom-input-com

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!