Почему форма React не регистрирует входные данные только в 3 полях? - PullRequest
0 голосов
/ 09 мая 2019

Эта форма, которую я делаю в приложении React, работала нормально, пока я не добавил еще несколько полей. Я не могу понять, почему я не смогу ввести в форму «имя», «отчество» или «фамилию».

По сути, я попытался добавить поля с точным процессом, с которым я добавил другие поля, но он просто не работает, и я продолжаю просматривать код и не могу выяснить, что происходит. Я добавляю в код все, что есть во всех других полях.

import React, { Component } from 'react';
import { Link, withRouter } from 'react-router-dom';
import { compose } from 'recompose';

import { withFirebase } from '../Firebase';
import * as ROUTES from '../../constants/routes';
import * as ROLES from '../../constants/roles';


const SignUpPage = () => (
  <div>
    <h1>SignUp</h1>
    <SignUpForm />
  </div>
);

const INITIAL_STATE = {
  username: '',
  firstName: '',
  middleName: '',
  lastName: '',
  email: '',
  passwordOne: '',
  passwordTwo: '',
  isAdmin: false,
  mailingAddress: '',
  city: '',
  state: '',
  zip: '',
  error: null,
};

class SignUpFormBase extends Component {
  constructor(props) {
    super(props);

    this.state = { ...INITIAL_STATE };
  }

  onChange = event => {
    this.setState({ [event.target.name]: event.target.value });
  };

  onSubmit = event => {

    const { username, firstName, middleName, lastName, email, passwordOne, isAdmin, mailingAddress, city, state, zip } = this.state;

    const roles = {};
    if (isAdmin) {
      roles[ROLES.ADMIN] = ROLES.ADMIN;
    }

    this.props.firebase
      .doCreateUserWithEmailAndPassword(email, passwordOne)
      .then(authUser => {
        // Create a user in your Firebase realtime database
        return this.props.firebase
          .user(authUser.user.uid)
          .set({
            username,
            firstName,
            middleName,
            lastName,
            email,
            roles,
            mailingAddress,
            city,
            state,
            zip,
          });
      })
      .then(() => {
        return this.props.firebase.doSendEmailVerification();
      })
      .then(() => {
        this.setState({ ...INITIAL_STATE });
        this.props.history.push(ROUTES.HOME);
      })
      .catch(error => {
        this.setState({ error });
      });

    event.preventDefault();

  }

  onChangeCheckbox = event => {
    this.setState({ [event.target.name]: event.target.checked });
  };

  onChangeSelection = event => {
    this.setState({ [event.target.name]: event.target.selected });
  };

  render() {

    const {
      username,
      firstName,
      middleName,
      lastName,
      email,
      passwordOne,
      passwordTwo,
      isAdmin,
      mailingAddress,
      city,
      state,
      zip,
      error,
    } = this.state;

    const isInvalid =
      passwordOne !== passwordTwo ||
      passwordOne === '' ||
      username === '' ||
      email === '' ||
      firstName === '' ||
      lastName === ''||
      mailingAddress === '' ||
      city === '' ||
      state === '' ||
      zip === '';


    return (
      <form onSubmit={this.onSubmit}>

        <div class="form-row">

          <div class="form-group col-md-4">
            <input
              name="username"
              value={username}
              onChange={this.onChange}
              type="text"
              placeholder="Username"
              class="form-control"
            />
          </div>

        </div>

        <div class="form-row">

          <div class="form-group col-md-4">
            <input
              name="firstname"
              value={firstName}
              onChange={this.onChange}
              type="text"
              placeholder="First Name"
              class="form-control"
            />
          </div>

          <div class="form-group col-md-4">
            <input
              name="middlename"
              value={middleName}
              onChange={this.onChange}
              type="text"
              placeholder="Middle Name"
              class="form-control"
            />
          </div>

          <div class="form-group col-md-4">
            <input
              name="lastname"
              value={lastName}
              onChange={this.onChange}
              type="text"
              placeholder="Last Name"
              class="form-control"
            />
          </div>

        </div>

        <div class="form-row">

          <div class="form-group col-md-12">
            <input
              name="email"
              value={email}
              onChange={this.onChange}
              type="text"
              placeholder="Email Address"
              class="form-control"
            />
          </div>

        </div>

        <div class="form-row">

          <div class="form-group col-md-6">
            <input
              name="passwordOne"
              value={passwordOne}
              onChange={this.onChange}
              type="password"
              placeholder="Password"
              class="form-control"
            />
          </div>

          <div class="form-group col-md-6">
            <input
              name="passwordTwo"
              value={passwordTwo}
              onChange={this.onChange}
              type="password"
              placeholder="Confirm Password"
              class="form-control"
            />
          </div>

        </div>

        <div class="form-row">

          <div class="form-group col-md-2">
            <label>
              Admin:
              <input
                name="isAdmin"
                type="checkbox"
                checked={isAdmin}
                onChange={this.onChangeCheckbox}
              />
            </label>
          </div>

        </div>
        <br />

        <div class="form-row">

          <div class="form-group col-md-4">
            Mailing Address:
            <input
              name="mailingAddress"
              value={mailingAddress}
              onChange={this.onChange}
              type="text"
              placeholder="Street Address"
              class="form-control"
            />
          </div>

        </div>

        <div class="form-row">

          <div class="form-group col-md-4">
            <input
              name="city"
              value={city}
              onChange={this.onChange}
              type="text"
              placeholder="City"
              class="form-control"
            />
          </div>

          <div class="form-group col-md-2">
            <select id="inputState" class="form-control" value={state} onChange={this.onChangeSelection}>
              <option selected>Choose a state</option>
              <option>...</option>
            </select>
          </div>

          <div class="form-group col-md-1">
            <input
              name="zip"
              value={zip}
              onChange={this.onChange}
              type="text"
              placeholder="Zip Code"
              class="form-control"
            />
          </div>

        </div>

        <button disabled={isInvalid} type="submit" class="btn btn-primary">
          Sign Up
        </button>

        {error && <p>{error.message}</p>}
      </form>
    );
  }
}

const SignUpLink = () => (
  <p>
    Don't have an account? <Link to={ROUTES.SIGN_UP}>Sign Up</Link>
  </p>
);

const SignUpForm = compose(
  withRouter,
  withFirebase,
)(SignUpFormBase);

export default SignUpPage;

export { SignUpForm, SignUpLink };

Я просто хочу, чтобы поля имени регистрировали нажатия клавиш, как и остальные формы. Все остальное работает. Я не понимаю, почему имя, отчество и фамилия будут только фокусироваться.

1 Ответ

0 голосов
/ 09 мая 2019

Попробуйте изменить value на defaultValue. defaultValue устанавливается только при начальной загрузке формы. После этого он не будет обновляться «естественным образом», поскольку целью было только установить начальное значение по умолчанию.

import React, { Component } from 'react';
import { Link, withRouter } from 'react-router-dom';
import { compose } from 'recompose';

import { withFirebase } from '../Firebase';
import * as ROUTES from '../../constants/routes';
import * as ROLES from '../../constants/roles';


const SignUpPage = () => (
  <div>
    <h1>SignUp</h1>
    <SignUpForm />
  </div>
);

const INITIAL_STATE = {
  username: '',
  firstName: '',
  middleName: '',
  lastName: '',
  email: '',
  passwordOne: '',
  passwordTwo: '',
  isAdmin: false,
  mailingAddress: '',
  city: '',
  state: '',
  zip: '',
  error: null,
};

class SignUpFormBase extends Component {
  constructor(props) {
    super(props);

    this.state = { ...INITIAL_STATE };
  }

  onChange = event => {
    this.setState({ [event.target.name]: event.target.value });
  };

  onSubmit = event => {

    const { username, firstName, middleName, lastName, email, passwordOne, isAdmin, mailingAddress, city, state, zip } = this.state;

    const roles = {};
    if (isAdmin) {
      roles[ROLES.ADMIN] = ROLES.ADMIN;
    }

    this.props.firebase
      .doCreateUserWithEmailAndPassword(email, passwordOne)
      .then(authUser => {
        // Create a user in your Firebase realtime database
        return this.props.firebase
          .user(authUser.user.uid)
          .set({
            username,
            firstName,
            middleName,
            lastName,
            email,
            roles,
            mailingAddress,
            city,
            state,
            zip,
          });
      })
      .then(() => {
        return this.props.firebase.doSendEmailVerification();
      })
      .then(() => {
        this.setState({ ...INITIAL_STATE });
        this.props.history.push(ROUTES.HOME);
      })
      .catch(error => {
        this.setState({ error });
      });

    event.preventDefault();

  }

  onChangeCheckbox = event => {
    this.setState({ [event.target.name]: event.target.checked });
  };

  onChangeSelection = event => {
    this.setState({ [event.target.name]: event.target.selected });
  };

  render() {

    const {
      username,
      firstName,
      middleName,
      lastName,
      email,
      passwordOne,
      passwordTwo,
      isAdmin,
      mailingAddress,
      city,
      state,
      zip,
      error,
    } = this.state;

    const isInvalid =
      passwordOne !== passwordTwo ||
      passwordOne === '' ||
      username === '' ||
      email === '' ||
      firstName === '' ||
      lastName === ''||
      mailingAddress === '' ||
      city === '' ||
      state === '' ||
      zip === '';


    return (
      <form onSubmit={this.onSubmit}>

        <div class="form-row">

          <div class="form-group col-md-4">
            <input
              name="username"
              defaultValue={username}
              onChange={this.onChange}
              type="text"
              placeholder="Username"
              class="form-control"
            />
          </div>

        </div>

        <div class="form-row">

          <div class="form-group col-md-4">
            <input
              name="firstname"
              defaultValue={firstName}
              onChange={this.onChange}
              type="text"
              placeholder="First Name"
              class="form-control"
            />
          </div>

          <div class="form-group col-md-4">
            <input
              name="middlename"
              value={middleName}
              onChange={this.onChange}
              type="text"
              placeholder="Middle Name"
              class="form-control"
            />
          </div>

          <div class="form-group col-md-4">
            <input
              name="lastname"
              defaultValue={lastName}
              onChange={this.onChange}
              type="text"
              placeholder="Last Name"
              class="form-control"
            />
          </div>

        </div>

        <div class="form-row">

          <div class="form-group col-md-12">
            <input
              name="email"
              value={email}
              onChange={this.onChange}
              type="text"
              placeholder="Email Address"
              class="form-control"
            />
          </div>

        </div>

        <div class="form-row">

          <div class="form-group col-md-6">
            <input
              name="passwordOne"
              value={passwordOne}
              onChange={this.onChange}
              type="password"
              placeholder="Password"
              class="form-control"
            />
          </div>

          <div class="form-group col-md-6">
            <input
              name="passwordTwo"
              value={passwordTwo}
              onChange={this.onChange}
              type="password"
              placeholder="Confirm Password"
              class="form-control"
            />
          </div>

        </div>

        <div class="form-row">

          <div class="form-group col-md-2">
            <label>
              Admin:
              <input
                name="isAdmin"
                type="checkbox"
                checked={isAdmin}
                onChange={this.onChangeCheckbox}
              />
            </label>
          </div>

        </div>
        <br />

        <div class="form-row">

          <div class="form-group col-md-4">
            Mailing Address:
            <input
              name="mailingAddress"
              value={mailingAddress}
              onChange={this.onChange}
              type="text"
              placeholder="Street Address"
              class="form-control"
            />
          </div>

        </div>

        <div class="form-row">

          <div class="form-group col-md-4">
            <input
              name="city"
              value={city}
              onChange={this.onChange}
              type="text"
              placeholder="City"
              class="form-control"
            />
          </div>

          <div class="form-group col-md-2">
            <select id="inputState" class="form-control" value={state} onChange={this.onChangeSelection}>
              <option selected>Choose a state</option>
              <option>...</option>
            </select>
          </div>

          <div class="form-group col-md-1">
            <input
              name="zip"
              value={zip}
              onChange={this.onChange}
              type="text"
              placeholder="Zip Code"
              class="form-control"
            />
          </div>

        </div>

        <button disabled={isInvalid} type="submit" class="btn btn-primary">
          Sign Up
        </button>

        {error && <p>{error.message}</p>}
      </form>
    );
  }
}

const SignUpLink = () => (
  <p>
    Don't have an account? <Link to={ROUTES.SIGN_UP}>Sign Up</Link>
  </p>
);

const SignUpForm = compose(
  withRouter,
  withFirebase,
)(SignUpFormBase);

export default SignUpPage;

export { SignUpForm, SignUpLink };
...