通过单击按钮更改输入值

Change input value through click on button

我目前正在努力使用按钮 "Auto generate link"。单击后,字段 "link" 应填充数据“http://predefinedlink.com

由于这里使用了 Formik + Material UI 的组合,我很难做到这一点。

const useStyles = makeStyles((theme) => ({[...]}));

const EventStream = ({ onSubmit, eventStream }) => {
  const classes = useStyles();

  return (
    <Formik
      initialValues={{
        link: maybe(() => eventStream.link, "") || "",
      }}
      onSubmit={onSubmit}
      validateOnBlur={false}
      validateOnChange={false}
      enableReinitialize
    >
      {({ handleSubmit, isSubmitting, dirty }) => (
        <FormikForm autoComplete="off" noValidate>
          <Card>
            <CardContent>
              <Grid container spacing={3}>
                <Grid xs={12} item>
                  <Field name="link" label="Link" component={TextField} />
                  <button
                    onClick={console.log("Fill TextField 'link' with new data")}
                  >
                    Auto generate link &raquo;
                  </button>
                </Grid>
              </Grid>
            </CardContent>
            <CardActions className={classes.cardActions}>
              <Button
                variant="contained"
                color="primary"
                classes={{
                  root: clsx(classes.saveButton, {
                    [classes.saveButtonDirty]: !dirty,
                  }),
                  disabled: isSubmitting && classes.saveButtonDisabled,
                }}
                disabled={isSubmitting || !dirty}
                onClick={handleSubmit}
              >
                Save
                {isSubmitting && (
                  <CircularProgress
                    size={20}
                    thickness={5}
                    color="inherit"
                    className={classes.saveButtonProgress}
                  />
                )}
              </Button>
            </CardActions>
          </Card>
        </FormikForm>
      )}
    </Formik>
  );
};

export default EventStream;

您可能需要使用 setFieldValue

{({ handleSubmit, isSubmitting, dirty }) => (

{({ handleSubmit, isSubmitting, dirty, setFieldValue  }) => (

按钮点击处理程序

             <button
                onClick={()=> {

                 setFieldValue ('link',  'http://predefinedlink.com')
                 }
               }
              >
                Auto generate link &raquo;
              </button>