[英]How to automatically click submit button - react
我有一個手動輸入用戶名和密碼的反應登錄頁面,
我希望提交按鈕在頁面加載時自動單擊,以便自動登錄用戶。
這是我的代碼。
export const LoginForm = () => {
const history = useHistory();
const classes = useStyles();
const email = 'email@email.com';
const password = 'mypassword';
const [authStatus, setStatus] = useState(null);
const [isSpinnerHidden, setSpinner] = useState(true);
const { session } = useContext(SessionContext);
const recaptchaRef = useRef();
const _onSubmit = async (e) => {
e.preventDefault();
setSpinner(false);
const authResult = await session.signIn(email, password);
setSpinner(true);
console.log(session);
authResult ? setStatus(authResult) : history.push('/dashboard');
};
return (
<form onSubmit={_onSubmit}>
<Typography
align='center'
color='primary'
variant="h4"
style={{ marginBottom: '20px' }}
>
Sign In
</Typography>
{authStatus ?
<Alert
severity="error"
>
{authStatus}
</Alert>
:
null
}
<TextField
type='email'
label="Email"
/>
<TextField
type='password'
label="Password"
/>
<Link
onClick={() => history.push('/restore')}
className={classes.restore}>
Forgot password?
</Link>
<MuiButton
text='Sign In'
type='submit'
value='login'
isSpinnerHidden={isSpinnerHidden}
className={classes.button}
/>
</form>
);
};
我可以在此代碼中添加什么或進行更改以使其自動單擊登錄按鈕並登錄用戶。
我不認為自動單擊按鈕是您在這里可以獲得的最佳體驗。
更好的方法是在渲染登錄屏幕之前根據身份驗證 state 有條件地選擇路由。 像這樣的東西:
if (isAuthenticated){
history.push('/dashboard);
} else {
history.push('/login');
}
如果出於某種原因您需要按照自己的方式進行操作,只需在使用 useEffect 安裝組件時調用您的登錄 function
import React, {useEffect} from 'react';
export const LoginForm = () => {
...
useEffect(() => {
if(isAuthenticated){ // You'll need to get the auth state from somewhere here
history.push('/dashboard')
}
},[])
return (
...
);
};
為了自動點擊提交按鈕,你需要使用一個onLoad
將您的 _onSubmit 轉換為 windows onload,像這樣
window.onload = async (e) => {
e.preventDefault();
setSpinner(false);
console.log('hello');
const authResult = await session.signIn(email, password);
setSpinner(true);
console.log(session);
authResult ? setStatus(authResult) : history.push('/dashboard');
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.