reactjs - 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.
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;
解决方案
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;
您可以进一步采用这种方法并将验证移动到您检查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;
推荐阅读
- ruby - 如果其他情况,请使用保护进行 ruby 转换引发异常
- c - 如何连接字符串但保留每个单独的空终止符?
- jekyll - Jekyll 4.0 构建失败并出现 NoMethodError
- php - OpenId 使用 php 或 Java 脚本连接
- php - 损坏的 PHP if-elseif 语句
- php - AWS - ElasticBeanstalk - PHP 平台 - 运行 NPM 命令
- data-structures - 链表插入和显示
- c# - 依赖的依赖;.net Core 3.0 中的 Framework 4.6.2 依赖项
- sql-server - 从表中的字符串中获取最后一个单词
- swift - iOS 13 导航栏奇怪的行为