问题摘要 您好团队,我是 Polaris 的新手,并尝试使用以下代码创建反应注册表单
import React, { useCallback, useState } from "react";
import {
Button,
Form,
FormLayout,
Layout,
Checkbox,
Card,
Page,
TextField,
} from "@shopify/polaris";
export const SignIn = () => {
const [textFieldValue, setTextFieldValue] = useState("Mark");
const [newsletter, setNewsletter] = useState(false);
const [email, setEmail] = useState("mark@hello.com");
const [password, setPassword] = useState("password");
const [loading, setLoading] = useState(false);
const handleNewsLetterChange = useCallback(
(value) => setNewsletter(value),
[]
);
const handleEmailChange = useCallback((value) =>{setEmail(value)}, [email]);
const handlePasswordChange = useCallback((value) => setPassword(value), [password]);
const handleTextFieldChange = useCallback(
(value) => setTextFieldValue(value),
[textFieldValue]
);
const handleSubmit = useCallback((_event) => {
// setLoading(true);
console.log(textFieldValue,newsletter,email, password )
}, []);
const signupForm = (
<Form onSubmit={handleSubmit} preventDefault={true}>
{console.log(email)}
<FormLayout>
<TextField
label="Name"
value={textFieldValue}
onChange={handleTextFieldChange}
error={textFieldValue ? "" : "Name is required"}
/>
<TextField
value={email}
onChange={handleEmailChange}
label="Email"
type="email"
error={email ? "" : "Email is required"}
helpText={
<span>
We’ll use this email address to inform you on future changes to
Polaris.
</span>
}
/>
<TextField
value={password}
onChange={handlePasswordChange}
label="Password"
type="password"
error={password ? "" : "Password is required"}
helpText={
<span>
We’ll use this email address to inform you on future changes to
Polaris.
</span>
}
/>
<Checkbox
label="Sign up for the newsletter"
checked={newsletter}
onChange={handleNewsLetterChange}
/>
<Button
submit
primary={true}
loading={loading}
fullWidth={true}
id="marketing-button"
>
Create your account
</Button>
</FormLayout>
</Form>
);
return (
<Page>
<Layout>
<Layout.Section secondary>
<Card title="Signup" sectioned>
{signupForm}
</Card>
</Layout.Section>
</Layout>
</Page>
);
};
当 Onchange 所有值都得到更新但使用 onsubmit useCallback 我只得到使用 useState 分配的旧值时,我尝试使用 onsubmit 作为正常功能,如下面的代码
const handleSubmit = () => {
console.log(textFieldValue,newsletter,email, password )
}
预期行为 由于我想将所有数据发送到 API,请教我如何使用 useCallback 执行此操作,否则我可以使用正常的 onSubmit 函数