React Formik Material UI自动完成功能:如何在localStorage的自动完成功能中填充值?

时间:2019-12-09 13:26:06

标签: reactjs material-ui formik

因此,我正在尝试使用Formik和Material UI创建表单。对于所有字段,一切都可以正常工作,但是问题在于自动完成功能。我找不到从localStorage填充字段的方法。我尝试了一切,从放置值props,inputValue,defaultValue等开始,但似乎没有任何效果。

import React from 'react'
import { Grid } from '@material-ui/core'
import { Autocomplete } from '@material-ui/lab'
import { Formik, Form, Field } from 'formik'
import { TextField } from 'formik-material-ui'
import * as yup from 'yup'
import { nationality } from '../../constants/nationality'
import Button from '../Button/Button'

export default function ForeignAddress () {

  let localStorageData = localStorage.getItem('foreignAddress'),
    retrivedData = JSON.parse(localStorageData)


  const handleNextClick = () => {
    console.log('clicked next')
  }

  const handleBackClick = () => {
    console.log('clicked back')
  }

  const validationSchema = yup.object({
    streetName: yup.string().required('Street name is required'),
    streetNumber: yup.string().required('Street number is required'),
    postalCode: yup.string().required('Postal code is required'),
    city: yup.string().required('City is required'),
    country: yup.string().required('Country is required'),
  })

  console.log(retrivedData)

  return (
    <React.Fragment>
      <div className="pages-wrapper address">
        <Formik
          initialValues={retrivedData ? retrivedData : {streetName: '', streetNumber: '', postalCode: '', city: '', coAddress: '', country: ''}}
          onSubmit={(data) => {
            console.log(data)
            localStorage.setItem('foreignAddress', JSON.stringify(data))
            handleNextClick()
          }}
          validationSchema={validationSchema}
        >
          {({setFieldValue}) => (
            <Form>
              <Grid container spacing={3}>
                <Grid item xs={12} md={8}>
                  <Field component={TextField} name="streetName" label="Street Name" variant="outlined" fullWidth />
                </Grid>
                <Grid item xs={12} md={4}>
                  <Field component={TextField} name="streetNumber" label="Street Number" variant="outlined" fullWidth />
                </Grid>
                <Grid item xs={12} md={4}>
                  <Field component={TextField} name="postalCode" label="Postal Code" variant="outlined" fullWidth />
                </Grid>
                <Grid item xs={12} md={8}>
                  <Field component={TextField} name="city" label="City" variant="outlined" fullWidth />
                </Grid>
                <Grid item xs={12} md={6}>
                  <Field component={TextField} name="coAddress" label="C/O Address" variant="outlined" fullWidth />
                </Grid>
                <Grid item xs={12} md={6}>
                  <Autocomplete
                    id="foreignCountry"
                    className="country-select"
                    name="country"
                    options={nationality}
                    getOptionLabel={option => option.label}
                    onChange={(e, value) => {
                      console.log(value)
                      setFieldValue("country", value.code)
                    }}
                    renderInput={params => (
                      <Field component={TextField} {...params} name="country" label="Country" variant="outlined" fullWidth/>
                    )}
                  />
                </Grid>
              </Grid>
              <div className="button-wrapper">
                <Button label="Back" go="back" handleClick={handleBackClick}/>
                <Button label="Next" go="next" type="submit" />
              </div>
            </Form>
          )}
        </Formik>
      </div>
    </React.Fragment>
  )
}

编辑:

感谢@Vencovsky我能够完成它

以防将来有人需要,这里是工作代码。 只需将自动完成组件更改为

<Autocomplete
  id="foreignCountry"
  className="country-select"
  name="country"
  options={nationality}
  getOptionLabel={option => option.label}
  defaultValue={values.country}
  onChange={(e, value) => {
    console.log(value)
    setFieldValue("country", value)
}}
  renderInput={params => (
    <Field component={TextField} {...params} name="country" label="Country" variant="outlined" fullWidth/>
)}
/>

在Formik道具中只需添加值道具

{({setFieldValue, values}) => (
   <Form>,...

1 个答案:

答案 0 :(得分:0)

编辑:

您需要更改一些内容。

首先,您不能只存储代码以便以后加载,而是需要存储选项中的所有内容(孔value对象)。

country: ''的初始值更改为country: {code: "", label: "", phone: ""},这是所有选项的默认值。

然后要正确加载值,您应该传递value={values.country},其中values来自formik道具。

然后在onChange上保存孔值onChange={(e, value) => {setFieldValue("country", value); }}

但是您也正在导入和使用一些错误的东西,例如

  <Field
    component={TextField}
    {...params}
    name="country"
    label="Country"
    variant="outlined"
    fullWidth
  />

Field是formik形式,TextField来自formik材质用户界面。

不确定为什么要使用它,但是我已经更改了。

这里是working example