我有條件地渲染 2 個<Formik/>組件,但值不會改變
function App() {
const [state, setState] = useState(true);
return (
<div>
<button
onClick={() => {
setState((s) => !s);
}}
>
toggle
</button>
<h1>Sign Up</h1>
{state ? (
<Formik
initialValues={{
firstName: "",
lastName: "",
email: ""
}}
onSubmit={async (values) => {
await new Promise((r) => setTimeout(r, 500));
alert(JSON.stringify(values, null, 2));
}}
>
<Form>
<div>
<label htmlFor="firstName">First Name</label>
<Field id="firstName" name="firstName" placeholder="Jane" />
</div>
<div>
<label htmlFor="lastName">Last Name</label>
<Field id="lastName" name="lastName" placeholder="Doe" />
</div>
<div>
<label htmlFor="email">Email</label>
<Field
id="email"
name="email"
placeholder="[email protected]"
type="email"
/>
</div>
<button type="submit">Submit</button>
</Form>
</Formik>
) : (
<Formik
initialValues={{
fn: "",
ln: ""
}}
onSubmit={async (values) => {
await new Promise((r) => setTimeout(r, 500));
alert(JSON.stringify(values, null, 2));
}}
>
<Form>
<div>
<label htmlFor="fn">F N</label>
<Field id="fn" name="fn" placeholder="Jane" />
</div>
<div>
<label htmlFor="ln">L N</label>
<Field id="ln" name="ln" placeholder="Doe" />
</div>
<button type="submit">Submit</button>
</Form>
</Formik>
)}
</div>
);
}
https://codesandbox.io/s/nifty-fast-4ef5r?file=/src/App.js
在上面的代碼和框中嘗試切換和提交
即使切換后初始值保持不變
內部發生了什么導致這種行為?
uj5u.com熱心網友回復:
React / Formik 必須在兩個實體中參考相同的背景關系,因為它們在相同的位置呈現。要解決此問題,請在兩個表單上放置不同的“key”屬性。
function App() {
const [state, setState] = useState(true);
return (
<div>
<button
onClick={() => {
setState((s) => !s);
}}
>
toggle
</button>
<h1>Sign Up</h1>
{state ? (
<Formik
key="1"
initialValues={{
firstName: "",
lastName: "",
email: ""
}}
onSubmit={async (values) => {
await new Promise((r) => setTimeout(r, 500));
alert(JSON.stringify(values, null, 2));
}}
>
<Form>
<div>
<label htmlFor="firstName">First Name</label>
<Field id="firstName" name="firstName" placeholder="Jane" />
</div>
<div>
<label htmlFor="lastName">Last Name</label>
<Field id="lastName" name="lastName" placeholder="Doe" />
</div>
<div>
<label htmlFor="email">Email</label>
<Field
id="email"
name="email"
placeholder="[email protected]"
type="email"
/>
</div>
<button type="submit">Submit</button>
</Form>
</Formik>
) : (
<Formik
key="2"
initialValues={{
fn: "",
ln: ""
}}
onSubmit={async (values) => {
await new Promise((r) => setTimeout(r, 500));
alert(JSON.stringify(values, null, 2));
}}
>
<Form>
<div>
<label htmlFor="fn">F N</label>
<Field id="fn" name="fn" placeholder="Jane" />
</div>
<div>
<label htmlFor="ln">L N</label>
<Field id="ln" name="ln" placeholder="Doe" />
</div>
<button type="submit">Submit</button>
</Form>
</Formik>
)}
</div>
);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/350330.html
標籤:javascript 反应 形式 福米克
