繁体   English   中英

如何将 onChange 添加到我的 onClick function?

[英]How can I add onChange to my onClick function?

一直在努力尝试解决这个问题,

我有一个<form>使用渲染包裹在 Controller 周围。 渲染是<Chip>的列表。 我希望芯片列表充当一个字段,每个用户切换的芯片将充当输入到表单的数据,基于芯片的 label 值。 预期数据可以是一个字符串,也可以是一组字符串,具体取决于切换的<Chips>数量。

我尝试复制使用<Checkbox>的示例,但无法重新创建组件。

我有一个 state 切换的总芯片,它重新生成了我想通过我的按钮提交的数据。 有没有办法将此 state 传递给我的表单数据?

我目前只能通过我的表格提交空数据,因为我的筹码值和表格数据没有正确链接。

为了解决这个问题,我需要在<Chip>onClick参数中添加onChange ,我试过这样做:

onClick={(value, e) => { handleToggle(value); onChange(value) }}

但这不起作用?

这是我的表格

        <form noValidate  onSubmit = { handleSubmit(onSubmit) }>
            <Controller
                    render={({ onChange ,...props }) => (
                        <Paper component="ul" className={classes.root}>
                            {stocklist.map((value, index) =>
                            {
                            return (
                            <li key={index}>
                            <Chip
                            name="stock_list"
                            variant="outlined"
                            label={value}
                            key={index}
                            color={checked.includes(value) ? 'secondary' : 'primary'}
                            onClick={handleToggle(value)}
                            className={classes.chip}
                            ref={register}
                            />
                            </li> 
                            );
                            })}
                        </Paper>
                    )}
                    name="stock_list"
                    control={control}
                    defaultValue={[]}
                    onChange={([, data]) => data}
                    />
                {checked && checked.length > 0 &&
                    <Fab
                        color="primary"
                        aria-label="delete"
                        type="submit"
                    >
                        <DeleteIcon />
                    </Fab>
                }
        </form>

这是我切换芯片的方法,并创建一个 state 检查它保存每个切换芯片的值

   const { register, control, handleSubmit } = useForm();
   const [checked, setChecked] = React.useState([]);

    const handleToggle = (value) => () => {
        const currentIndex = checked.indexOf(value);
        const newChecked = [...checked];
     
        if (currentIndex === -1) {
            newChecked.push(value);
        } else {
            newChecked.splice(currentIndex, 1);
        }
     
        setChecked(newChecked);
        };

这是我的 onSubmit function

    const onSubmit = (data, e) =>
      {  
        console.log(data);
    
        axiosInstance
          .patch('url', {
            stock_list: data.stock_list,
          })
          .then((res) =>
          {
            console.log(res);
            console.log(res.data);
          });
    };

检查一下https://codesandbox.io/s/cocky-roentgen-j0pcg请切换其中一个芯片,然后按下出现的按钮。 如果您随后检查控制台,您会注意到正在提交一个空的表单数组。

我想这对你有用

        import React, { useState } from "react";
        import { Chip, Paper, Fab, Grid } from "@material-ui/core/";
        import { makeStyles } from "@material-ui/core/styles";
        import { Controller, useForm } from "react-hook-form";
        import DeleteIcon from "@material-ui/icons/Delete";

        const useStyles = makeStyles((theme) => ({
          root: {
            display: "flex",
            justifyContent: "center",
            flexWrap: "wrap",
            listStyle: "none",
            padding: theme.spacing(0.5),
            margin: 0,
            "@media (max-width: 600px)": {
              overflowY: "auto",
              height: 200
            }
          },
          chip: {
            margin: theme.spacing(0.5)
          }
        }));

        export default function app() {
          const { register, control, handleSubmit } = useForm();
          const classes = useStyles();
          const [checked, setChecked] = React.useState([]);
          const stocklist = ["AAPL", "AMD", "TSLA"];

          const onSubmit = (data, e) => {
            console.log("data.stock_list");
            console.log(data.stock_list);
            console.log("data.stock_list");
          };

          const handleToggle = (value) => {// <== I changed this part
            const currentIndex = checked.indexOf(value);
            const newChecked = [...checked];

            if (currentIndex === -1) {
              newChecked.push(value);
            } else {
              newChecked.splice(currentIndex, 1);
            }
            setChecked(newChecked);
            return newChecked;// <== I changed this part
          };

          return (
            <>
              {(!stocklist || stocklist.length === 0) && (
                <p style={{ textAlign: "center" }}>Your Bucket is empty...</p>
              )}
              {stocklist && stocklist.length > 0 && (
                <Grid>
                  <form noValidate onSubmit={handleSubmit(onSubmit)}>
                    <Controller
                      name="stock_list"// <== I changed this part
                      render={({ onChange, ...props }) => (
                        <Paper component="ul" className={classes.root}>
                          {stocklist.map((value, index) => {
                            return (
                              <li key={index}>
                                <Chip
                                  // name="stock_list"// <== I changed this part
                                  variant="outlined"
                                  label={value}
                                  key={index}
                                  color={
                                    checked.includes(value) ? "secondary" : "primary"
                                  }
                                  onClick={(e) => {
                                    onChange(handleToggle(value));// <== I changed this part
                                  }}
                                  className={classes.chip}
                                  ref={register}
                                />
                              </li>
                            );
                          })}
                        </Paper>
                      )}
                      control={control}
                      defaultValue={{}}
                      onChange={([, data]) => data}
                    />
                    {checked && checked.length > 0 && (
                      <Fab color="primary" aria-label="delete" type="submit">
                        <DeleteIcon />
                      </Fab>
                    )}
                  </form>
                </Grid>
              )}
            </>
          );
        }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM