首页 > 解决方案 > 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>
        );
    };
}

标签: javascriptreactjs

解决方案


您只需添加autoFocus到要自动对焦的输入即可。

 <input autoFocus />

推荐阅读