【问题标题】:Ref with custom class - reactdate picker带有自定义类的 Ref - reactdate 选择器
【发布时间】:2020-11-06 00:55:10
【问题描述】:

当在较早的组件(输入字段)上按下回车时,我试图将焦点设置在反应日期选择器上。 我阅读了官方文档,并且使用了简单字段的示例,但是当我使用 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>
);

}

来自类的sn-p代码是:

     <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()

【问题讨论】:

    标签: reactjs ref reactstrap


    【解决方案1】:
    1. 使用setFocus() 而不是focusDatePicker中没有focus

    2. 在功能组件中,使用 props 传递 ref 引用不是有效的方式。 你需要知道Forwarding 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)
    

    【讨论】:

    • 我还需要改变什么,你有什么指示吗?
    • @Qli 那么,可能是时间问题。您是否在安装时立即调用您的函数?
    • 你能打电话给ref={(input) =&gt; { input.focus()}}
    • 我编辑了我的答案,我添加了一个代码,我调用一个函数来设置焦点
    • @Qli DatePicker中有函数名focus吗???代码中似乎是setFocus...github.com/Hacker0x01/react-datepicker/blob/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-09-08
    • 1970-01-01
    • 2018-02-12
    • 2015-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多