React Formik Material UI自动完成功能:如何在localStorage的自动完成功能中填充值? [英] React Formik Material UI Autocomplete: How can I populate value inside of autocomplete from localStorage?

查看:90
本文介绍了React Formik Material UI自动完成功能:如何在localStorage的自动完成功能中填充值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

So, I'm trying to create form with Formik and Material UI. For all the fields everything is working as it should but the problem is with Autocomplete. I cannot find the way to populate the field from the localStorage. I tried everything, from putting the value props, inputValue, defaultValue, etc but nothing seems to work.

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我能够完成它

Thanks to @Vencovsky i was able to get it done

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

in case someone in the future needs this here is the working code. Just change Autocomplete component to

<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道具中只需添加值道具

and in the Formik props just add values prop

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

推荐答案

您需要更改一些内容.

There is a few thing you need to change.

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

First you can't just store the code to load it later, you need to store everything (the hole value object) from the options.

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

Change the initial value of country: '' to country: {code: "", label: "", phone: ""} which is all the default value of the options.

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

Then to load the value correctly you should pass value={values.country} where values comes from formik props.

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

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

But you are also importing and using some wrong things like

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

Field是formik形式,而TextField是formik材质ui.

Where Field is form formik and TextField from formik material ui.

不知道为什么要这样使用它,但我已经对其进行了更改.

Not sure why you use it like that, but I have changed it.

这是一个工作示例

这篇关于React Formik Material UI自动完成功能:如何在localStorage的自动完成功能中填充值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆