【发布时间】:2020-10-30 18:24:17
【问题描述】:
我有一个这样的对象数组:
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>
现在,我需要根据第一个选择输入中的项目选择来更新第二个选择项的值。例如,当我从第一个选择中选择“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>
)
}导出默认的AddNewForm;
【问题讨论】:
-
你使用的是类还是函数组件?
-
到目前为止您尝试过什么?是否创建了 Field 组件的 onChange/onSelect 方法?
-
我正在使用功能组件并添加了我迄今为止一直在使用的组件,是的,我知道我应该传递一个 onChange 处理程序方法,但不确定实现该操作的逻辑是什么
-
您能否在代码沙箱或其他任何地方创建此问题的副本?这样我就可以查看错误(如果有)。
-
@ManishSundriyal,这是我们一直在尝试修复的沙盒链接stackblitz.com/edit/react-wp4tmq。 “级别”字段仍然存在一个问题。即使根据国家/地区的选择过滤了 level 的值,在 OnSubmit 上传递的值仍然为空,除非我们更改“level”字段中的值。如果你能帮助我们就好了