首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何从外部更改Formik TextField值?

如何从外部更改Formik TextField值?
EN

Stack Overflow用户
提问于 2020-04-19 11:04:39
回答 3查看 7.6K关注 0票数 5

在模块对话框中,我想更改输入值(#quaggaIsbn)的值。我尝试了document.getElementById("quaggaIsbn").value = result.codeResult.code,但它没有反映到表单发送到服务器的值。如何更改Formik发送到服务器的值?

NewProjectDialog.js

代码语言:javascript
运行
复制
import React from 'react';
import PropTypes from 'prop-types'
import { Formik, Field, Form } from 'formik'
import { TextField} from 'formik-material-ui'
import { makeStyles } from '@material-ui/core/styles'
import Button from '@material-ui/core/Button'
import Dialog from '@material-ui/core/Dialog'
import DialogTitle from '@material-ui/core/DialogTitle'
import DialogActions from '@material-ui/core/DialogActions'
import DialogContent from '@material-ui/core/DialogContent'
import styles from './NewProjectDialog.styles'
import Quagga from 'quagga';

const useStyles = makeStyles(styles)

function NewProjectDialog({ onSubmit, open, onRequestClose }) {
  const classes = useStyles()

  function handleSubmit(values, { setSubmitting }) {
    return onSubmit(values).then(() => {
      setSubmitting(false)
    })
  }



  function inputFile(){
    const file = document.getElementById("quaggaFile").files[0];
    const reader = new FileReader();
    reader.addEventListener("load", function () {
      // convert image file to base64 string
      analyzeQuaggaFile(reader.result);
      //preview.src = reader.result;
    }, false);
    reader.readAsDataURL(file);
  }

  function analyzeQuaggaFile(src){
  Quagga.decodeSingle({
//    src: "/image-002.jpg",
    src: src,
    numOfWorkers: 0,  // Needs to be 0 when used within node
    inputStream: {
        size: 800  // restrict input-size to be 800px in width (long-side)
    },
    decoder: {
        readers: ["ean_reader"] // List of active readers
    },
  }, function(result) {
      if(result.codeResult) {
          console.log("result", result.codeResult.code);
          document.getElementById("quaggaIsbn").value = result.codeResult.code  ;
      } else {
          console.log("not detected");
      }
  });
}

  return (
    <Dialog open={open} onClose={onRequestClose}>
      <DialogTitle id="new-project-dialog-title">Sell book</DialogTitle>

      <Formik initialValues={{ name: '' }} onSubmit={handleSubmit}>
        {({ errors, isSubmitting }) => (
          <Form className={classes.root}>
            <DialogContent>
              <Field
                id="quaggaIsbn"
                name="isbn"
                label="ISBN"
                component={TextField}
                margin="normal"
                fullWidth
              />
              Scan bar code:<input id="quaggaFile" type="file" accept="image/*" capture="camera" onChange={inputFile}/>
              <Field
                name="title"
                label="Title"
                component={TextField}
                margin="normal"
                fullWidth
              />
              <Field
                name="status"
                label="Status"
                component={TextField}
                margin="normal"
                fullWidth
              />
              <Field
                name="price"
                label="Price"
                component={TextField}
                margin="normal"
                fullWidth
              />
              Book cover:<input id="image" type="file"/>
            </DialogContent>
            <DialogActions>
              <Button onClick={onRequestClose} color="secondary">
                Cancel
              </Button>
              <Button type="submit" color="primary" disabled={isSubmitting}>
                {isSubmitting ? 'Creating...' : 'Create'}
              </Button>
            </DialogActions>
          </Form>
        )}
      </Formik>


    </Dialog>
  )
}

NewProjectDialog.propTypes = {
  onSubmit: PropTypes.func.isRequired,
  open: PropTypes.bool.isRequired,
  onRequestClose: PropTypes.func.isRequired
}

export default NewProjectDialog
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2020-04-19 18:05:15

here render方法提供了一个使用Formik prop手动更改字段值的方法,它将字段名和新值作为参数,如果要了解更多信息,请参阅Formik

至于你需要改变的地方在这里

代码语言:javascript
运行
复制
// accept a new parameter which you can pass to the `analyzeQuaggaFile` function
function inputFile(setFieldValue) {
  const file = document.getElementById("quaggaFile").files[0];

  const reader = new FileReader();

  reader.addEventListener(
    "load",
    function () {
      // pass the setFieldValue
      analyzeQuaggaFile(reader.result, setFieldValue);
    },
    false
  );

  reader.readAsDataURL(file);
}

// second parameter is setFieldValue
function analyzeQuaggaFile(src, setFieldValue) {
  Quagga.decodeSingle(
    {
      src: src,
      numOfWorkers: 0,
      inputStream: {
        size: 800,
      },
      decoder: {
        readers: ["ean_reader"],
      },
    },
    function (result) {
      if (result.codeResult) {
        // update the isbn field value
        setFieldValue("isbn", result.codeResult.code);
      } else {
        console.log("not detected");
      }
    }
  );
}

现在,在您的JSX代码中更改以下内容:

代码语言:javascript
运行
复制
<Formik initialValues={{ name: "" }} onSubmit={handleSubmit}>
  {({ errors, isSubmitting, setFieldValue }) => (
    <Form className={classes.root}>
      {/* Other fields */}
      Scan bar code:
      <input
        id="quaggaFile"
        type="file"
        accept="image/*"
        capture="camera"
        onChange={() => inputFile(setFieldValue)} // pass the setFieldValue property from formik 
      />
      {/* Other fields */}
    </Form>
  )}
</Formik>;
票数 3
EN

Stack Overflow用户

发布于 2020-12-13 03:20:28

使用enableReinitialize属性在上下文之外更新Formik属性后,可以使整个Formik重置。

https://formik.org/docs/api/formik#enablereinitialize-boolean

如下所示:

代码语言:javascript
运行
复制
<Formik validationSchema={validationSchema} initialValues={this.state.formValues} onSubmit={this.handleFormSubmission} enableReinitialize={true}>
票数 5
EN

Stack Overflow用户

发布于 2021-05-22 07:17:17

代码语言:javascript
运行
复制
    import {
      useFormik
    } from "formik";
    import * as yup from 'yup';

    export default function ChangeFormikValueOutsideForm() {
      const initialValues = {
        first_name: 'John',
        last_name: 'Doe'
      }
      const validationSchema = yup.object({
        first_name: yup.string("must be a string")
          .required("Must have a first name"),
        last_name: yup.string("must be a string")
      })
      const formik = useFormik({
          initialValues,
          validationSchema,
          onSubmit: (values) => {}
        )
      }
    }

    let handleLastNameChange = () => {
      formik.setFieldValue('last_name', Math.ceil(Math.random() * 100))
    }

    return (
    <form onSubmit = {
        formik.handleSubmit
      } >
      <p> First Name * </p> 
      <input
        name = "first_name"
        id = "first_name"
        type = "text"
        onChange = {
          formik.handleChange
        }
        value = {
          formik.values.first_name
        }
      />
      <p> Last Name </p>
      <input
        name = "last_name"
        id = "last_name"
        type = "text"
        onChange = {
          handleLastNameChange
        }
        value = {
          formik.values.last_name
        }
      />
      <input
        type = "submit"
        value = "Submit Form"
      />
      </form>
      )
    }

它与formik钩子一起工作,这允许您在useFormik标记之外定义表单,然后从formik变量中受益,从而在表单之外执行setFieldValue方法。实际上,您完全是在表单之外处理表单;)

使用material ui的想法也是一样的。它起作用了

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61299042

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档