在表字段中添加数据后,我需要将字段设置为初始状态

发布于 2025-01-23 21:37:33 字数 3996 浏览 0 评论 0原文

我想通过单击添加按钮将数据添加到表之后,将所有textfield设置为初始状态,

我可以通过使用nistionsearchesform.resetform(); 但是,如果我在添加按钮中设置此会发生什么情况,请在此处重置数据,但我的表数据也会被删除,因为它已更新了Formik values setteamData([[values,... ... TeamSdata]);

i在ONCLICK之后,它在此状态中添加formik值会添加它,但是如果我重置表单并设置初始状态值也将设置为空,因此将数据添加到表 textfield 获取重置或初始化但 则表数据将保持不变

如果我们不尝试这样的方式,

          <Button
            onClick={() => {
              AssignSearchesForm.handleSubmit();
              // I tried this two way
              //first way
              // AssignSearchesForm.resetForm();

              //second way
              // AssignSearchesForm.setFieldValue("selectName","")
              // AssignSearchesForm.setFieldValue("selectAge","")
              // AssignSearchesForm.setFieldValue("location","")
            }}
            variant="contained"
          >
            Add
          </Button>
export default function App() {
  const [teamdata, setTeamData] = React.useState([]);

  const AssignSearchesForm = useFormik({
    initialValues: {
      selectName: "",
      selectAge: "",
      location: ""
    },
    validationSchema,
    onSubmit: (values) => {
      setTeamData([values, ...teamdata]);
    }
  });

  let filteredArray = nameList.filter(
    (e) => !teamdata.some((data) => data.selectName === e.selectName)
  );

  const handleChange = (e) => {
    const selectedName = e.target.value;
    const name = nameList.find((data) => data.selectName === selectedName);
    const newOptions = Object.values(name).reduce((optionList, key) => {
      optionList.push({ value: key, label: key });
      return optionList;
    }, []);
    AssignSearchesForm.setFieldValue("selectName", selectedName);
    AssignSearchesForm.setFieldValue("selectAge", newOptions[1]?.value || "");
    AssignSearchesForm.setFieldValue("location", newOptions[2]?.value || "");
  };

  return (
    <div className="App">
      <Grid container direction="row" spacing={1}>
        <Grid item xs={4}>
          <TextField
            sx={{ minWidth: 150 }}
            select
            id="outlined-basic"
            label="Select Name"
            name="selectName"
            size="small"
            onChange={handleChange}
            value={AssignSearchesForm.values.selectName}
            error={
              AssignSearchesForm.errors.selectName &&
              AssignSearchesForm.touched.selectName
            }
          >
            {filteredArray?.map((option) => (
              <MenuItem key={option.selectName} value={option.selectName}>
                {option.selectName}
              </MenuItem>
            ))}
          </TextField>
        </Grid>
        <Grid item xs={4}>
          <TextField
            id="outlined-basic"
            label="location"
            name="location"
            size="small"
            {...AssignSearchesForm.getFieldProps("location")}
          />
        </Grid>
        <Grid item xs={4}>
          <TextField
            id="outlined-basic"
            label="Select Age"
            name="selectAge"
            size="small"
            {...AssignSearchesForm.getFieldProps("selectAge")}
          />
        </Grid>
        <Grid item xs={4}>
          <Button
            onClick={() => {
              AssignSearchesForm.handleSubmit();
              // AssignSearchesForm.resetForm();
              // AssignSearchesForm.setFieldValue("selectName","")
              // AssignSearchesForm.setFieldValue("selectAge","")
              // AssignSearchesForm.setFieldValue("location","")
            }}
            variant="contained"
          >
            Add
          </Button>
        </Grid>
      </Grid>

      <Table teamdata={teamdata} />
    </div>
  );
}

I want to set all TextField to the initial state after adding data to the table by clicking ADD button

I am able to set that to the initial state by using AssignSearchesForm.resetForm(); but what happens here if I set this in add button click it will reset data but my table data also get removed because it's updated Formik values setTeamData([values, ...teamdata]);

I am adding Formik value in this state after onClick it will get added but if I reset form and set initial this state value also getting set empty so what I want after adding data into table TextField get reset or initial but table data will stay the same either if we do not update that

This way I am trying

          <Button
            onClick={() => {
              AssignSearchesForm.handleSubmit();
              // I tried this two way
              //first way
              // AssignSearchesForm.resetForm();

              //second way
              // AssignSearchesForm.setFieldValue("selectName","")
              // AssignSearchesForm.setFieldValue("selectAge","")
              // AssignSearchesForm.setFieldValue("location","")
            }}
            variant="contained"
          >
            Add
          </Button>
export default function App() {
  const [teamdata, setTeamData] = React.useState([]);

  const AssignSearchesForm = useFormik({
    initialValues: {
      selectName: "",
      selectAge: "",
      location: ""
    },
    validationSchema,
    onSubmit: (values) => {
      setTeamData([values, ...teamdata]);
    }
  });

  let filteredArray = nameList.filter(
    (e) => !teamdata.some((data) => data.selectName === e.selectName)
  );

  const handleChange = (e) => {
    const selectedName = e.target.value;
    const name = nameList.find((data) => data.selectName === selectedName);
    const newOptions = Object.values(name).reduce((optionList, key) => {
      optionList.push({ value: key, label: key });
      return optionList;
    }, []);
    AssignSearchesForm.setFieldValue("selectName", selectedName);
    AssignSearchesForm.setFieldValue("selectAge", newOptions[1]?.value || "");
    AssignSearchesForm.setFieldValue("location", newOptions[2]?.value || "");
  };

  return (
    <div className="App">
      <Grid container direction="row" spacing={1}>
        <Grid item xs={4}>
          <TextField
            sx={{ minWidth: 150 }}
            select
            id="outlined-basic"
            label="Select Name"
            name="selectName"
            size="small"
            onChange={handleChange}
            value={AssignSearchesForm.values.selectName}
            error={
              AssignSearchesForm.errors.selectName &&
              AssignSearchesForm.touched.selectName
            }
          >
            {filteredArray?.map((option) => (
              <MenuItem key={option.selectName} value={option.selectName}>
                {option.selectName}
              </MenuItem>
            ))}
          </TextField>
        </Grid>
        <Grid item xs={4}>
          <TextField
            id="outlined-basic"
            label="location"
            name="location"
            size="small"
            {...AssignSearchesForm.getFieldProps("location")}
          />
        </Grid>
        <Grid item xs={4}>
          <TextField
            id="outlined-basic"
            label="Select Age"
            name="selectAge"
            size="small"
            {...AssignSearchesForm.getFieldProps("selectAge")}
          />
        </Grid>
        <Grid item xs={4}>
          <Button
            onClick={() => {
              AssignSearchesForm.handleSubmit();
              // AssignSearchesForm.resetForm();
              // AssignSearchesForm.setFieldValue("selectName","")
              // AssignSearchesForm.setFieldValue("selectAge","")
              // AssignSearchesForm.setFieldValue("location","")
            }}
            variant="contained"
          >
            Add
          </Button>
        </Grid>
      </Grid>

      <Table teamdata={teamdata} />
    </div>
  );
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

枯寂 2025-01-30 21:37:33

您可以在onsubmit formik的功能中利用第二个参数formikhelper

在评论中,Dev-Developter指出的更好方法:

onSubmit: (values, formikHelper) => {
      setTeamData([values, ...teamdata]);
      formikHelper.resetForm();
    }

如果resetform()没有用,则另一种替代方法无用。

onSubmit: (values, formikHelper) => {
      setTeamData([values, ...teamdata]);
      formikHelper.setFieldValue("selectName", "");
      formikHelper.setFieldValue("selectAge", "");
      formikHelper.setFieldValue("location", "");
    }

这是修改后的 code sandbox

You can leverage the second parameter formikHelper in onSubmit function of formik.

Better approach pointed out by dev-developer in comments:

onSubmit: (values, formikHelper) => {
      setTeamData([values, ...teamdata]);
      formikHelper.resetForm();
    }

Another alternative approach if resetForm() is not useful.

onSubmit: (values, formikHelper) => {
      setTeamData([values, ...teamdata]);
      formikHelper.setFieldValue("selectName", "");
      formikHelper.setFieldValue("selectAge", "");
      formikHelper.setFieldValue("location", "");
    }

Here is the modified code sandbox

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文