首页 > 解决方案 > 带有自定义类的 Ref - reactdate 选择器

问题描述

当在较早的组件(输入字段)上按下回车时,我试图将焦点设置在反应日期选择器上。我阅读了官方文档,并且使用了简单字段的示例,但是当我使用 DatePicker 进行更改时,出现了一个旧错误

TypeError: this.inputAccountDate.focus is not a function

我的功能是:

function CustomDatePicker(props) {
return (
    <div>
        {/* <input ref={props.innerRef} /> */}
            <DatePicker className="form-control" 
                placeholderText="Izaberite datum"
                dateFormat="dd/MM/yyyy"
                maxDate={new Date()}
                ref={props.innerRef}
        />
    </div>
);

}

带有表单的类的代码段是:

     <Col className="pr-md-1" md="3">
        <FormGroup >
          <label>Datum računa</label>
           <div>
               <CustomDatePicker
                  innerRef={(input) => { this.inputAccountDate = input }}
                  />
           </div>
          </FormGroup>
      </Col>

我调用函数来设置焦点的组件是

 <Col className="pr-md-1" md="3">
   <FormGroup>
      <label>Broj računa</label>
      <Input style={{'borderColor':'lightgray', 'fontSize':'14px'}}
         innerRef={(input) => { this.inputAccountNumber = input }}
         onKeyDown={this.focusAccountDate}
         placeholder="Br.računa"
         type="text"
         value={this.state.accountNumber || (header === null ? "" : 
             header.account_number) }
         onChange={this.changeAccountNumber}
         onFocus={(e)=>e.target.select()}
         required
        />
       </FormGroup>
    </Col>

管理焦点的功能

    focusAccountDate = (e) => {
    if(e !== undefined) {
        if(e.key === 'Enter') {
            this.inputAccountDate.focus()
        }
    }
}

和 inputAccountDate 是this.inputAccountDate = React.createRef()

标签: reactjsrefreactstrap

解决方案


  1. 使用setFocus()而不是focus. focus里面没有DatePicker

  2. 在功能组件中,使用 props 传递 ref 引用不是有效的方式。你需要知道转发参考

您的 CustomDatePicker 应更改如下。

function CustomDatePicker(props, ref) {
  return (
    <div>
            <DatePicker className="form-control" 
                placeholderText="Izaberite datum"
                dateFormat="dd/MM/yyyy"
                maxDate={new Date()}
                ref={ref}
        />
    </div>
  );
}

export default React.forwardRef(CustomDatePicker)

推荐阅读