javascript - ReactJS Cannot get input autofocus to work
问题描述
Exploring ReactJS and attempting to create a base component called "TextField". If the focus property exists then the field is supposed to set focus after the component mounts. I have the following code but I can't track down why the setting the focus does not work:
import React, { Component } from "react";
import "./inputs.css";
export const TextField = class TextField extends Component {
constructor(props){
super(props);
this.myRef = React.createRef();
}
componentDidMount(){
if(this.props.focus){
this.myRef.current.focus();
}
}
render(){
var errid = this.props.id + "_errmsg";
var labelStyle = "w3-label-font";
var inputStyle = "w3-input w3-border w3-light-grey w3-round";
return(
<div>
<label className={labelStyle}><b>{this.props.label}</b></label>
<input className={inputStyle} type={this.props.type} id={this.props.id} name={this.props.name} ref={this.myRef}/>
<div id={errid} className="error-msg"></div>
</div>
);
};
}
解决方案
您只需添加autoFocus
到要自动对焦的输入即可。
<input autoFocus />
推荐阅读
- mongodb - 在 Meteor/MongoDB 中删除数组对象
- javascript - 在使用 express 的 axios 请求后重新启动服务器
- nginx - 如何为每个位置块手动设置静态 html 文件
- c# - 选择文件时不发送表单值
- html - 每次我重新加载页面时滚动条会下降吗?
- objective-c - 连接到 MFP 8.0 时无效的安全检查 RegisteredClient
- function - 方案错误“应用程序:不是程序”
- batch-file - 没有匹配的 URL - 将文件复制到谷歌云存储时
- go - 如何将巨大的 csv 数据(4GB)转储到 mysql 中
- android - Gradle 错误:升级到新的 Google 服务后,项目的多个变体 :myModule 与消费者属性匹配