我有一个像这样的对象数组:
const items = [
{ country:"USA", level:1},
{ country:"Canada", level:2},
{ country:"Bangladesh", level:3},
]
Run Code Online (Sandbox Code Playgroud)
在我的 Form 组件中(我使用的是 React Formik 库),我正在渲染这样的项目:
<Field name="color" as="select" placeholder="Favorite Color">
{items.map((item,index)=>(
<option>{item.country}</option>
))}
</Field>
<Field name="color" as="select" placeholder="Favorite Color">
{items.map((item,index)=>(
<option>{item.level}</option>
))}
</Field>
Run Code Online (Sandbox Code Playgroud)
现在,我需要根据第一个选择输入中的项目选择来更新第二个选择项目的值。例如,当我从第一个选择中选择“USA”然后在第二个选择中它会更新值并呈现“1”。任何想法或建议将不胜感激。到目前为止,我的组件如下所示:
import React from 'react';
import { Formik, Field } from 'formik';
import { Modal } from 'react-bootstrap';
const AddNewForm = () => {
const items = [
{ country:"USA", level:1},
{ country:"Canada", level:2},
{ country:"Bangladesh", level:3},
]
const handleUpdate = () => {
console.log("change value...")
}
return (
<div>
<Formik
initialValues={{ country: '', level: '' }}
onSubmit={(values, { setSubmitting }) => {
setTimeout(() => {
alert(JSON.stringify(values, null, 2));
setSubmitting(false);
}, 400);
}}
>
{({
values,
errors,
touched,
handleChange,
handleBlur,
handleSubmit,
isSubmitting,
/* and other goodies */
}) => (
<form onSubmit={handleSubmit}>
<Field name="country" as="select" onChange={handleUpdate}>
{items.map((item,index)=>(
<option>{item.country}</option>
))}
</Field>
<Field name="level" as="select">
{items.map((item,index)=>(
<option>{item.level}</option>
))}
</Field>
<Modal.Footer>
<button type="submit" disabled={isSubmitting}>
Save
</button>
</Modal.Footer>
</form>
)}
</Formik>
</div>
)
Run Code Online (Sandbox Code Playgroud)
}导出默认AddNewForm;
正如我之前写的……不需要手动管理状态,Formik 为我们管理它。
使用时需要具有功能组件/钩子的版本useFormikContext(以及<Formi />作为父/上下文提供程序)<Field/>。您可以useFormik(并且没有父级)与普通的 html 输入一起使用。
外部组件:
export default function App() {
const items = [
{ country: "USA", level: 1 },
{ country: "USA", level: 5 },
{ country: "Canada", level: 2 },
{ country: "Canada", level: 4 },
{ country: "Bangladesh", level: 2 },
{ country: "Bangladesh", level: 7 }
];
return (
<div className="App">
<h1>connected selects</h1>
<Formik
initialValues={{ country: "", level: "" }}
onSubmit={values => {
console.log("SUBMIT: ", values);
}}
>
<Form data={items} />
</Formik>
</div>
);
}
Run Code Online (Sandbox Code Playgroud)
外部组件(父级<Formik />)职责:
内部组件职责:
内部组件:
import React, { useState, useEffect } from "react";
import { Field, useFormikContext } from "formik";
import { Modal } from "react-bootstrap";
const AddNewForm = props => {
const items = props.data;
// derived data, calculated once, no updates
// assuming constant props - for changing useEffect, like in levelOptions
const [countryOptions] = useState(
Array.from(new Set(items.map(item => item.country)))
);
const [levelOptions, setLevelOptions] = useState([]);
const {
values,
handleChange,
setFieldValue,
handleSubmit,
isSubmitting,
isValid // will work with validation schema or validate fn defined
} = useFormikContext();
const myHandleChange = e => {
const selectedCountry = e.target.value;
debugger;
// explore _useFormikContext properties
// or FormikContext in react dev tools
console.log("myHandle selectedCountry", selectedCountry);
handleChange(e); // update country
// available levels for selected country
const levels = items.filter(item => item.country === selectedCountry);
if (levels.length > 0) {
// update level to first value
setFieldValue("level", levels[0].level);
console.log("myHandle level", levels[0].level);
}
};
// current values from Formik
const { country, level } = values;
// calculated ususally on every render
//
// const countryOptions = Array.from(new Set(items.map(item => item.country)));
// const levelOptions = items.filter(item => item.country === country);
//
// converted into hooks (useState and useEffect)
//
useEffect(() => {
// filtered array of objects, can be array of numbers
setLevelOptions(items.filter(item => item.country === country));
}, [items, country]); // recalculated on country [or items] change
return (
<div>
<form onSubmit={handleSubmit}>
<Field
name="country"
value={country}
as="select"
onChange={myHandleChange} // customized handler
>
{!country && (
<option key="empty" value="">
Select Country - disappearing empty option
</option>
)}
{countryOptions.map((country, index) => (
<option key={country} value={country}>
{country}
</option>
))}
</Field>
{country && (
<>
<Field
name="level"
as="select"
onChange={handleChange} // original handler
>
{levelOptions.map((item, index) => (
<option key={item.level} value={item.level}>
{item.level}
</option>
))}
</Field>
<Modal.Footer>
<button type="submit" disabled={!isValid && isSubmitting}>
Save
</button>
</Modal.Footer>
</>
)}
</form>
<>
<h1>values</h1>
{country && country}
<br />
{level && level}
</>
</div>
);
};
export default AddNewForm;
Run Code Online (Sandbox Code Playgroud)
它是否满足所有功能要求?
| 归档时间: |
|
| 查看次数: |
4758 次 |
| 最近记录: |