[英]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.