如何使用 React 根据前 select 项的 selection 更新 select 项
How to update select items based on the selection from the first select items using react
我有一个这样的对象数组:
const items = [
{ country:"USA", level:1},
{ country:"Canada", level:2},
{ country:"Bangladesh", level:3},
]
在我的表单组件中(我正在使用 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>
现在,我需要根据第一个 select 输入的项目 selection 更新第二个 select 项目的值。例如,当我将从第一个 selection select "USA" 然后在第二个 selection 中更新值并呈现“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>
)
}导出默认的 AddNewForm;
试试这个。
import React, {useState} 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 },
];
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={handleChange} >
<option value='' defaultValue>Select Country</option>
{items.map((item, index) => (
<>
<option value={item.country} >{item.country}</option>
</>
))}
</Field>
<Field name="level" as="select" onChange={handleChange} >
<option value='' defaultValue>Select Level</option>
{items.filter((item)=>item.country===values.country).map((item, index) => (
<option>{item.level}</option>
))}
</Field>
<Modal.Footer>
<button type="submit" disabled={isSubmitting}>
Save
</button>
</Modal.Footer>
</form>
)}
</Formik>
</div>
);
};
export default AddNewForm;
试试这个工作 demo
正如我之前写的...不需要手动管理状态,Formik 会为我们管理它。
具有功能 conponents/hooks 的版本 - useFormikContext
(和 <Formi />
作为 parent/context 提供者)在使用 <Field/>
时需要。您可以使用 useFormik
(而不是 parent)和正常的 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>
);
}
外部组件(parent <Formik />
)职责:
- 初始化
- 主要处理程序(提交)
- 验证
内部组件责任:
- 数据作为道具传递;
- 本地数据过滤(用hooks避免不必要的重新计算);
- 字段依赖的本地处理程序;
- 视觉条件变化
内部组件:
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;
工作demo, explorable/debbugable iframe here
它是否满足所有功能要求?
我有一个这样的对象数组:
const items = [
{ country:"USA", level:1},
{ country:"Canada", level:2},
{ country:"Bangladesh", level:3},
]
在我的表单组件中(我正在使用 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>
现在,我需要根据第一个 select 输入的项目 selection 更新第二个 select 项目的值。例如,当我将从第一个 selection select "USA" 然后在第二个 selection 中更新值并呈现“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>
)
}导出默认的 AddNewForm;
试试这个。
import React, {useState} 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 },
];
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={handleChange} >
<option value='' defaultValue>Select Country</option>
{items.map((item, index) => (
<>
<option value={item.country} >{item.country}</option>
</>
))}
</Field>
<Field name="level" as="select" onChange={handleChange} >
<option value='' defaultValue>Select Level</option>
{items.filter((item)=>item.country===values.country).map((item, index) => (
<option>{item.level}</option>
))}
</Field>
<Modal.Footer>
<button type="submit" disabled={isSubmitting}>
Save
</button>
</Modal.Footer>
</form>
)}
</Formik>
</div>
);
};
export default AddNewForm;
试试这个工作 demo
正如我之前写的...不需要手动管理状态,Formik 会为我们管理它。
具有功能 conponents/hooks 的版本 - useFormikContext
(和 <Formi />
作为 parent/context 提供者)在使用 <Field/>
时需要。您可以使用 useFormik
(而不是 parent)和正常的 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>
);
}
外部组件(parent <Formik />
)职责:
- 初始化
- 主要处理程序(提交)
- 验证
内部组件责任:
- 数据作为道具传递;
- 本地数据过滤(用hooks避免不必要的重新计算);
- 字段依赖的本地处理程序;
- 视觉条件变化
内部组件:
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;
工作demo, explorable/debbugable iframe here
它是否满足所有功能要求?