【问题标题】:react-day-picker custom input loses focus when onDayChange selects a day当 onDayChange 选择一天时,react-day-picker 自定义输入失去焦点
【发布时间】:2020-08-13 04:46:55
【问题描述】:

我正在尝试将DayPickerInput 与我自己的自定义输入一起使用,但是在键入输入时,一旦选择了一天,就会失去焦点。如果尝试输入例如:2020-08-20,则可以看到这一点,当输入到达“2020-08-2”时,它会选择 2nd 作为日期并取消输入焦点,不允许用户到达 20。

Here 是一个代码沙箱,我在其中复制了问题。

DayPickerInput的用法:

<DayPickerInput
        component={(props) => <CustomInput {...props} />}
        value={value}
        onDayChange={setValue} />

还有我的自定义输入组件:

import React from "react";

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} />;
  }
}

export default Input;

我已经看到this 问题,并尝试了那里的解释,但它不起作用,我不知道还能尝试什么。

感谢任何指导!谢谢!

【问题讨论】:

  • 你可以尝试将“hideOnDayClick={false}”作为道具添加到 DayPickerInput 中,这样可以让它保持打开状态
  • 添加 hideOnDayClick 并没有改变任何东西,因为覆盖层之前仍处于打开状态,只是从输入中失去焦点

标签: reactjs react-day-picker


【解决方案1】:

我觉得有点傻,因为我一发布问题就找到了解决方案。尽管如此,它还是以防万一其他人也有同样的问题。

我必须添加一个转发的引用,以便在我的onDayChange 函数中我可以调用ref.current.focus(),现在保持焦点。这是最终代码:(我相信沙盒已更新为正确的解决方案,因为我正在玩它)

function Example() {
  const [value, setValue] = React.useState(null);
  const ref = React.useRef(null);
  return (
    <div>
      <h3>DayPickerInput</h3>
      <DayPickerInput
        component={React.forwardRef((props, ref) => <CustomInput {...props} innerRef={ref}/>)}
        value={value}
        inputProps={{ ref: ref }}
        onDayChange={async day => {
           await setValue(day);
           // need to call focus here to keep focus on the input
           ref.current.focus();
        }}
      />
    </div>
  );
}

并且在自定义输入中,该组件中不再定义ref,而是通过props转发:

import React from "react";

class Input extends React.Component {
  focus() {
    this.props.innerRef.current.focus();
  }

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

export default Input;

【讨论】:

    猜你喜欢
    • 2020-01-26
    • 2019-10-10
    • 1970-01-01
    • 2021-05-29
    • 2019-09-27
    • 2012-09-28
    • 2021-04-02
    • 2019-01-02
    • 2017-09-17
    相关资源
    最近更新 更多