探索 ReactJS 并尝试创建一个名为“TextField”的基本组件。如果 focus 属性存在,则该字段应该在组件安装后设置焦点。我有以下代码,但我无法找出为什么设置焦点不起作用:
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 />
关于javascript - ReactJS 无法让输入自动对焦工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57402206/