我正在學習 React 并致力于我的寵物專案。所以,我有一個帶有自定義輸入組件的表單,我只想在用戶單擊按鈕時驗證它們,但我不知道如何進行。全輸入檢查是表單是否不為空并正確填寫。我試圖創建一個模型來訂閱按鈕點擊事件的組件,但是當表單正確填寫時,狀態不是在 1 次之后更新,而是在 2 次點擊之后,我不知道為什么。
import React from "react";
import ReactDOM from "react-dom";
import "./style.css";
function validate(name, email, password) {
// we are going to store errors for all fields
// in a signle array
const errors = [];
if (name.length === 0) {
errors.push("Name can't be empty");
}
if (email.length < 5) {
errors.push("Email should be at least 5 charcters long");
}
if (email.split("").filter(x => x === "@").length !== 1) {
errors.push("Email should contain a @");
}
if (email.indexOf(".") === -1) {
errors.push("Email should contain at least one dot");
}
if (password.length < 6) {
errors.push("Password should be at least 6 characters long");
}
return errors;
}
class SignUpForm extends React.Component {
constructor() {
super();
this.state = {
errors: []
};
this.handleSubmit = this.handleSubmit.bind(this);
}
handleSubmit(e) {
e.preventDefault();
const name = ReactDOM.findDOMNode(this._nameInput).value;
const email = ReactDOM.findDOMNode(this._emailInput).value;
const password = ReactDOM.findDOMNode(this._passwordInput).value;
const errors = validate(name, email, password);
if (errors.length > 0) {
this.setState({ errors });
return;
}
// submit the data...
}
render() {
const { errors } = this.state;
return (
<form onSubmit={this.handleSubmit}>
{errors.map(error => (
<p key={error}>Error: {error}</p>
))}
<input
ref={nameInput => (this._nameInput = nameInput)}
type="text"
placeholder="Name"
/>
<input
ref={emailInput => (this._emailInput = emailInput)}
type="text"
placeholder="Email"
/>
<input
ref={passwordInput => (this._passwordInput = passwordInput)}
type="password"
placeholder="Password"
/>
<button type="submit">Submit</button>
</form>
);
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<SignUpForm />, rootElement);
更多細節
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/367809.html
標籤:javascript 反应 打字稿
上一篇:發送整數值作為對NodeJSAPI呼叫的回應時未收到回應
下一篇:JS序列中出現的次數是素數
