首页 > 解决方案 > React - Pass form data into a function

问题描述

I am new to React and I have a dashboard to display all users. I created a new feature to add a new user on the dashboard. Currently there is only one field to fill out which is the email.

enter image description here

Dashboard.js

    <form id="new-user-form">
      <fieldset>
        <label>
          <p>Email</p>
          <input type="email" name="new-user" id="new-user" required />
        </label>
      </fieldset>
      <button
        type="button"
        form="new-user-form"
        onClick={this.onFormSubmit}
      >
        Add
      </button>
    </form>

and the method onFormSubmit function

onFormSubmit(event) {
    var new_email = document.getElementById("new-user").value;
    var today =
      new Date().getFullYear() +
      "-" +
      ("0" + (new Date().getMonth() + 1)).slice(-2) +
      "-" +
      ("0" + new Date().getDate()).slice(-2);

    let new_users = {
      email: new_email,
      registration: today,
      status: "disabled",
    };
    this.setState((prevState) => ({
      users: [...prevState.users, new_users],
    }));

What I currently have works but there is no data-validation, I can add a user with an empty form because the new_email variable is taking document.getElementById("new-user").value which can be empty and should rather be the form data.

If you wanna see my full code for dashboard.js

class Dashboard extends Component {
  constructor(props) {
    super(props);
    this.state = {
      users: [
        {
          email: "pierre-alexandre@gmail.com",
          registration: "2020-10-25",
          status: "active",
        },
        {
          email: "antoine373@gmail.com",
          registration: "2018-10-22",
          status: "active",
        },
        {
          email: "sofia.leduc@gmail.com",
          registration: "2020-01-03",
          status: "disabled",
        },
      ],
      searchEmail: "",
    };
    this.onFormSubmit = this.onFormSubmit.bind(this);
  }

  onFormSubmit(event) {
    var new_email = document.getElementById("new-user").value;
    var today =
      new Date().getFullYear() +
      "-" +
      ("0" + (new Date().getMonth() + 1)).slice(-2) +
      "-" +
      ("0" + new Date().getDate()).slice(-2);

    let new_users = {
      email: new_email,
      registration: today,
      status: "disabled",
    };
    this.setState((prevState) => ({
      users: [...prevState.users, new_users],
    }));
  }

  handleLogout = () => {
    fire.auth().signOut();
  };

  handleInput = (e) => {
    this.setState({ searchEmail: e.target.value });
  };

  render() {
    let filteredUsers = this.state.users.filter((user) => {
      return user.email
        .toLowerCase()
        .includes(this.state.searchEmail.toLowerCase());
    });
    return (
      <div>
        <h2>Welcome</h2>
        <button onClick={this.handleLogout}>Logout</button>
        <div className="users-dashboard-container">
          <div className="users-dashboard">
            <div className="top-navigation">
              <div className="search-navigation">
                <img
                  src={process.env.PUBLIC_URL + "images/search.png"}
                  alt="logo"
                />
                <SearchBox handleInput={this.handleInput} />
              </div>

              <div className="add-user">
                <a>Add user</a>
              </div>
            </div>
            <div class="dashboard-content">
              <table>
                <tr>
                  <th>Email</th>
                  <th>Registration Date</th>
                  <th>Status</th>
                  <th>Other</th>
                </tr>
                <UserList filteredUsers={filteredUsers} />
              </table>
            </div>
          </div>
        </div>
        <div>
          <div className="wrapper">
            <h1>Add a User</h1>
            <form id="new-user-form">
              <fieldset>
                <label>
                  <p>Email</p>
                  <input type="email" name="new-user" id="new-user" required />
                </label>
              </fieldset>
              <button
                type="button"
                form="new-user-form"
                onClick={this.onFormSubmit}
              >
                Add
              </button>
            </form>
          </div>
        </div>
      </div>
    );
  }
}

export default Dashboard;

标签: reactjs

解决方案


state.searchEmail一种简单的方法是在为空时禁用提交按钮。

import React, { Component } from "react";

class Dashboard extends Component {
  constructor(props) {
    super(props);
    this.state = {
      searchEmail: ""
    };
    this.onFormSubmit = this.onFormSubmit.bind(this);
    this.handleInput = this.handleInput.bind(this);
  }

  onFormSubmit() {
    let new_user = {
      email: this.state.searchEmail
    };
    console.log(new_user);
  }

  handleInput(e) {
    this.setState({ searchEmail: e.target.value });
  };

  render() {
    return (
      <form>
        <label>
          Email
          <input
            onChange={this.handleInput}
            value={this.state.searchEmail}
            type="email"
            required
          />
        </label>
        <button
          onClick={this.onFormSubmit}
          disabled={this.state.searchEmail === ""}
        >
          Add
        </button>
      </form>
    );
  }
}

export default Dashboard;

编辑 eager-fermat-g79ky


您可以进一步采用这种方法并将验证移动到您检查state.searchEmail正则表达式的函数中。

import React, { Component } from "react";

class Dashboard extends Component {
  constructor(props) {
    super(props);
    this.state = {
      searchEmail: ""
    };
  }

  onFormSubmit = (e) => {
    e.preventDefault();
    let new_user = {
      email: this.state.searchEmail
    };
    console.log(new_user);
    this.setState({ searchEmail: "" });
  };

  handleInput = (e) => {
    this.setState({ searchEmail: e.target.value });
  };

  formIsInvalid = () => {
    return (
      this.state.searchEmail === "" ||
      !this.state.searchEmail.match(/^[\w-.]+@([\w-]+\.)+[\w-]{2,4}$/)
    );
  };

  render() {
    return (
      <form action="" onSubmit={this.onFormSubmit}>
        <label>
          Email
          <input
            onChange={this.handleInput}
            value={this.state.searchEmail}
            type="email"
            required
          />
        </label>
        <button disabled={this.formIsInvalid()}>Add</button>
      </form>
    );
  }
}

export default Dashboard;

编辑 elated-lewin-4m8np


推荐阅读