繁体   English   中英

如何设置焦点需要属性<input> React 中的标签

[英]How to set focus require attribute on <input> tag in React

我有登录/注册 forms ,其中有几个input标签。

当我打开这个表单时,我想在第一个input标签上设置焦点和需要属性。

我尝试了 jQuery 和 JavaScript 代码,它在 require 属性上运行良好。

input标签的值为空时,它会显示警告警报,但设置焦点不起作用。

下面是我的代码。

<form className="Form_login">
    <h2>Login</h2>
    {location.state?.message && 
        (<div className="Message_login">
            {location.state?.message}
        </div>)}
    {error && <div className="Alert_login">{error}</div>}
    <label className="InputGroup_login" htmlFor="email">
        Email:
        <input className="Input_login"
               id="email"
               type="email"
               value={email}
               onChange={(e) => setEmail(e.target.value)}
        />
    </label>
    <label className="InputGroup_login" htmlFor="password">
        Password:
        <input className="Input_login"
               id="password"
               type="password"
               value={password}
               onChange={(e) => setPassword(e.target.value)}
        />
    </label>
    <div className="ButtonContainer_login">
        <button className="Button_addhome Input_addhome" 
                onClick={handleSubmit}>Login</button>
        <Link to = "/" 
              className="Button_link Input_addhome" 
              style={{textAlign:"center"}}>Cancel</Link>
    </div>
    <div style={{ textAlign: "center", paddingTop: "1rem" }}>
        <span>
            forgot password or <Link to="/register">register</Link>
        </span>
    </div>
</form>

请帮我。

您也可以尝试基于 jQuery 的方法:

$(document).ready(function() {
    $('form:first *:input[type!=hidden]:first').focus();
});

您可以设置 require 属性,只需在输入标签中添加required即可。 并且还通过在您的输入标签中添加autofocus属性来将焦点设置在第一个input标签上。

   <input className="Input_login
          id="email"
          type="email"
          value={email}
          onChange={(e) => setEmail(e.target.value)}
          required
          autofocus
    />

注意: autofocus属性不能用于hidden类型的输入,因为隐藏的输入不能被聚焦。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM