将复选框输出存储到全局状态

时间:2020-10-21 12:27:48

标签: javascript reactjs

我有一些用户必须填写的输入。其中之一是复选框。我希望我的复选框在切换或不切换时将其值传递给全局状态。 因此,在切换时,它将true存储在全局存储中,而在未切换时,false将存储在全局存储中。

目前,它不存储任何内容。它不会将任何值传递给全局存储。

这是我的StayForm.js

import React, {Component} from 'react';

import FormValuesContext from '../context/form-values-context';

export default class StayForm extends Component {

    static contextType = FormValuesContext;

    constructor() {
        super();

        this.handleSubmit = this.handleSubmit.bind(this);
    }
    
    handleSubmit(e) {
        e.preventDefault();
        e.stopPropagation();

        const data = new FormData(e.target);
        const form_data = {
            amount_of_people: data.get('amount_of_people'),
            arrival_date: data.get('arrival_date'),
            leave_date: data.get('leave_date'),
            use_electricity: data.get('use_electricity'),
            box_number: data.get('box_number')
        }

        if (this.context.validateFormData('stay_data', form_data)) {
            this.context.setFormData('stay_data', form_data);
            this.props.history.push('/control-page');
        }
    }

    render() {
        return (
            <section className="reservationForm">
                <form className="stayForm" onSubmit={this.handleSubmit}>
                    <div>
                        <div className="formControl">
                            <label htmlFor="amountOfPeople">Het aantal mensen</label>
                            <input
                                type={"number"}
                                step="1"
                                min="1"
                                max="12"
                                name="amount_of_people"
                                defaultValue={this.context.stay_data.amount_of_people}
                            />
                        </div>
                        <div className="formControl">
                            <label htmlFor="arrivalDate">Datum van aankomst</label>
                            <input
                                type="date"
                                name="arrival_date"
                                defaultValue={this.context.stay_data.arrival_date}
                            />
                        </div>
                        <div className="formControl">
                            <label htmlFor="leaveDate">Datum van vertrek</label>
                            <input
                                type="date"
                                name="leave_date"
                                defaultValue={this.context.stay_data.leave_date}
                            />
                        </div>
                        <div className="formControl">
                            <label htmlFor="useOfElectricity">Electriciteit bij verblijf</label>
                            <p>JA</p>
                            <input
                                type="checkbox"
                                name="use_of_electricity"
                                defaultValue={this.context.stay_data.use_of_electricity}
                            />
                        </div>
                        <div className="formControl">
                            <label htmlFor="boxNumber">Boxnummer</label>
                            <input
                                type="number"
                                name="box_number"
                                defaultValue={this.context.stay_data.box_number}
                            />
                        </div>
                        <input type="submit" value="Verder"/>
                    </div>
                </form>
            </section>
        )
    }
}

这是我的FormsValuesState.js

import React, { Component } from 'react';

import FormValuesContext from './form-values-context';

class FormValuesState extends Component {
  state = {
    personal_data: {
      first_name: '',
      last_name: '',
      e_mail: '',
      phone_number: '',
      completed: false,
    },
    boat_data: {
      boat_length: 0.0,
      boat_width: 0.0,
      boat_depth: 0.0,
      completed: false,
    },
    stay_data: {
      amount_of_people: 0,
      arrival_date: 0,
      leave_date: 0,
      use_electricity: false,
      box_number: 0,
      completed: false,
    },
    current_page: 0,
  };

  validateFormData = (scope, form_data) => {
    // alert(data.get('first_name'));
    // console.log(form_data);
    const current_state = this.state;

    // If validation successed...
    current_state[scope].completed = true;
    this.setState(current_state);
    return true;
  };

  getFormData = (scope) => {
    return this.state[scope];
  };

  setFormData = (scope, values) => {
    let current_state = this.state;
    current_state[scope] = values;
    this.setState(current_state);
    console.log(current_state);
  };

  getCurrentPage = () => {
    return this.state.current_page;
  };

  setCurrentPage = (page) => {
    this.setState({current_page: page});
  };

  render() {
    return (
      <FormValuesContext.Provider
        value={{
          personal_data: this.state.personal_data,
          boat_data: this.state.boat_data,
          stay_data: this.state.stay_data,
          validateFormData: this.validateFormData,
          getFormData: this.getFormData,
          setFormData: this.setFormData,
          getCurrentPage: this.getCurrentPage,
          setCurrentPage: this.setCurrentPage,
        }}
      >
        {this.props.children}
      </FormValuesContext.Provider>
    );
  }
}

export default FormValuesState;

这是我的form-values-context.js

import React from "react";

export default React.createContext({
  personal_data: {
    first_name: '',
    last_name: '',
    e_mail: '',
    phone_number: '',
    completed: false,
  },
  boat_data: {
    boat_length: 0.0,
    boat_width: 0.0,
    boat_depth: 0.0,
    completed: false,
  },
  stay_data: {
    amount_of_people: 0,
    arrival_date: 0,
    leave_date: 0,
    use_electricity: false,
    box_number: 0,
    completed: false,
  },
  current_page: 0,
  validateFormData: () => {},
  getFormData: () => {},
  setFormData: () => {},
  getCurrentPage: () => {},
  setCurrentPage: () => {},
});

非常感谢!

1 个答案:

答案 0 :(得分:1)

<input 
   type="checkbox"
   name="use_of_electricity"
   onChange(e => this.context.setFormData("stay_data", {
       ...this.context.stay_data,
       use_of_electricity: e.target.value
   })) 
   defaultValue={this.context.stay_data.use_of_electricity}
/>