我是js的新手,所以我对何时使用哪种类型的调用、任何帮助或任何链接都很困惑。
例如,在提交表单时,我使用了onSubmit={() => onSubmit()},但当我将其更改为onSubmit={onSubmit()}时,它不起作用,它起作用了
const onSubmit = async (e) => {
e.preventDefault();
const credentials = {
emailAddress: email.trim(),
password: password,
rememberMe: rememberMe,
};
if (!emailError && email && password) {
setLoading(true);
login(credentials)
.then((result) => {
setLoading(false);
if (result) {
setError(false);
window.location.assign('/');
} else {
setError(t('Login.InvalidCredentials'));
}
})
.catch((err) => {
setError(t('Login.ServerError'));
setLoading(false);
});
}
};
<Form fontColor={(props) => props.theme.colors.grey.base} onSubmit={onSubmit}>
<Loader visibility={loading} />
<LoginDiv>
<Label>{t('E-mail')}</Label>
<Input
id={'email'}
type={'email'}
placeholder={'johndoe@email.com'}
value={email}
onChange={(e) => emailValidation(e.target.value)}
/>
<Status>{emailError}</Status>
</LoginDiv>
<PasswordDiv>
<Label>{t('Password')}</Label>
<Input
id={'password'}
placeholder={'●●●●●●●●●●●●●●'}
value={password}
onChange={(e) => handlePassword(e)}
onKeyPress={() => handleKeyPress()}
/>
<IconDiv>
<Eye onClick={() => setShow(!showPassword)} />
</IconDiv>
</PasswordDiv>
<Column>
<ForgetText
onClick={() => props.history.push('/forgot_password')}
>
{t('Login.Forgotten')}
</ForgetText>
<Remember>
<label>
<Input
type={'checkbox'}
onClick={() => setRemeber(!rememberMe)}
value={rememberMe}
/>
{t('Login.Remember')}
</label>
</Remember>
</Column>
<Button
type='submit'
>
{t('Sign In')}
</Button>
</Form>那么为什么它现在能工作,为什么用这种方式不能工作(onSubmit={() => onSubmit()}),我不知道为什么以及什么时候使用哪个帮助会很有价值,或者任何链接,我知道这一点,并提前感谢使用:)
发布于 2020-10-01 20:59:24
这看起来像是将参数传递给处理程序函数的问题。() => onSubmit()在不传递参数的情况下调用函数,而onSubmit={onSubmit}告诉应该调用哪个函数,并将参数(表单数据)传递给它。这个答案可能会帮助你决定用哪种方式处理数据:link
发布于 2020-10-01 21:05:20
onSubmit={onSubmit}会将表单添加的任何参数传递给onSubmit={() => onSubmit()},而onSubmit不会传递任何参数。每次组件为onSubmit(...args)时,onSubmit={() => onSubmit()}都会创建函数() => onSubmit()请注意,如果您喜欢此onSubmit={onSubmit()},则每次组件呈现/重新呈现时都会调用它,这可能不是您最想要的。
https://stackoverflow.com/questions/64155513
复制相似问题