reactjs - 带有自定义类的 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()
解决方案
使用
setFocus()
而不是focus
.focus
里面没有DatePicker
在功能组件中,使用 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)
推荐阅读
- javascript - Javscript 搜索功能偶尔工作
- reactjs - 无法将 Material UI Labs 导入 React 应用程序
- kubernetes - 操作员控制器无法删除相关资源
- java - 如何使用 Spark Java 中的数据框构建基于其他列的列?
- angular - RXJS combineLatest issue after upgarde 5 to 6
- c# - .NET Core 中的过滤器顺序
- ios - Xcode 12 Storyboard Identitiy Inspector 找不到带有 iOS 12 设备的类
- java - 如何从英国政府冠状病毒 api 下载 csv
- javascript - 使用 JInt 解析和评估复杂对象
- c# - 用户登录时在 Windows\SysWOW64 中运行的程序,而不是 Program Files