简体   繁体   English

在 React 中根据状态设置表单的值

[英]Set the value of a form based on state in React

Using Formik for validating some fields, if a state value is true I want that the value of a fields to be copied to the value of another one.使用 Formik 验证某些字段,如果状态值为 true,我希望将字段的值复制到另一个字段的值。

For example, value of mainAddress to be copied to address .例如,要复制到addressmainAddress值。

There is a state variable, setAddress which is set on false but it can be changed to true when a checkbox is clicked.有一个状态变量setAddress设置为 false,但可以在单击复选框时将其更改为 true。

When this variable is set on true I want that the value of mainAddress to be copied to address当此变量设置为 true 时,我希望将mainAddress的值复制到address

This is the code that works fine without copying that value:这是无需复制该值即可正常工作的代码:

import React from 'react';
import { Formik, Form, Field } from 'formik';
import { Input, Button, Label, Grid } from 'semantic-ui-react';
import * as Yup from 'yup';
import { Creators } from '../../../actions';
import './CreateCompanyForm.scss';

class CreateCompanyForm extends React.PureComponent {
  constructor(props) {
    super(props);

    this.state = { // state variables 
      address: '',
      mainAddress: '',
      setAddress: false,
    };
  }

  handleSubmit = values => {
    // create company
  };

  toggleAddress = () => { // it toggles the value of setAddress
    this.setState(prevState => ({
      setAddress: !prevState.setAddress,
    }));
  };

  render() {
    const initialValues = { // the address and mainAddress are set to '' at the start
      address: '',
      mainAddress: '',
    };
    const validationSchema = Yup.object({
      address: Yup.string().required('error'),
      mainAddress: Yup.string().required('error'),
    });
    return (
      <>
        <Button type="submit" form="amazing"> // button for submit
          Create company
        </Button>

        <Formik
          htmlFor="amazing"
          initialValues={initialValues}
          validationSchema={validationSchema}
          onSubmit={values => this.handleSubmit(values)}>
          {({ values, errors, touched, setValues, setFieldValue }) => (
            <Form id="amazing">
              <Grid>
                <Grid.Column> // mainAddress value
                  <Label>Main Address</Label>
                  <Field name="mainAddress" as={Input} />
                </Grid.Column>

                <Grid.Column> // address value
                  <Label>Address</Label>
                  <Field name="address" as={Input} />
                  <div>
                    {this.state.setAddress // here is how I've tried to set that value
                      ? values.address.setFieldValue(values.mainAddress)
                      : console.log('nope')}
                    {touched.address && errors.address ? errors.address : null}
                  </div>
                </Grid.Column>
              </Grid>
              <Checkbox
                label="Use same address"
                onClick={() => this.toggleAddress()}
              />
            </Form>
          )}
        </Formik>
      </>
    );
  }
}

So I've tried more ways to solve it but without success.所以我尝试了更多的方法来解决它,但没有成功。 Now in the code it is:现在在代码中是:

 {this.state.setAddress
     ? values.address.setFieldValue(values.mainAddress)
     : console.log('nope')}

Other one was: (this.state.setAddress ? values.address = values.mainAddress)另一个是: (this.state.setAddress ? values.address = values.mainAddress)

None of them work.他们都没有工作。 Is it possible to get the value from values.mainAddress and copy it to values.address ?是否可以从values.mainAddress获取值并将其复制到values.address Or to its input?还是对其输入?

You can rewrite the Field component for address accordingly.您可以相应地重写地址的字段组件。

<Field name="address">
 {({
    field, // { name, value, onChange, onBlur }
 }) => {
   values.address = values.mainAddress;
   return (
     <div>
        <input
           {...field}
           type="text"
           placeholder="Address"
         />
      </div>
    );
  }}
</Field>

Here we are setting the value of address field to values.mainAddress if setAdress checkbox is checked else we let formik value to fill it.这里我们将地址字段的值设置为 values.mainAddress 如果 setAdress 复选框被选中,否则我们让 formik 值来填充它。

Here is the working codesandbox code - https://codesandbox.io/s/fervent-tereshkova-sro93?file=/index.js这是工作代码和框代码 - https://codesandbox.io/s/fervent-tereshkova-sro93?file=/index.js

Formik also provides values object you could use that for updating address value same as mainAddress. Formik 还提供了值对象,您可以使用它来更新与 mainAddress 相同的地址值。 Just provide name attribute to both input fields then assign like this - props.values.address = {...props.values.mainAddress}只需为两个输入字段提供名称属性,然后像这样分配 - props.values.address = {...props.values.mainAddress}

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

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