gpt4 book ai didi

reactjs - 如何使用 react 根据从第一个选择项目中的选择更新选择项目

转载 作者:行者123 更新时间:2023-12-04 00:57:39 26 4
gpt4 key购买 nike

我有一个这样的对象数组:

 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;

最佳答案

正如我之前写的... 无需手动管理状态,Formik 为我们管理 .
带有功能组件/ Hook 的版本 - 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>
);
}
外部组件(父级 <Formik /> )职责:
  • 初始化
  • 主要处理程序(提交)
  • 验证

  • 内部组件职责:
  • 作为 Prop 传递的数据;
  • 本地数据过滤(避免使用钩子(Hook)进行不必要的重新计算);
  • 字段依赖的本地处理程序;
  • 视觉条件变化

  • 内部组件:
    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 , 可探索/可调试的 iframe here
    它是否满足所有功能要求?

    关于reactjs - 如何使用 react 根据从第一个选择项目中的选择更新选择项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61087790/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com