Formularze
Budowanie
Pola formularzy dzielimy na kontrolowane (przez React) i nie kontrolowane. Poniższy przykład pokazuje różnicę ():
<input value="niekontrolowany" onChange={this.handleChange} />
<input value={this.state.value} onChange={this.handleChange} />
Zobacz przykład:
Zarządzanie stanem, walidacja
Aby zmiany były widoczne, musimy aktualizować wartość w state.value
:
class MyForm extends React.Component {
state = {value: ''};
handleChange = (event) => {
this.setState({ value: event.target.value });
}
render() {
return (
<input value={this.state.value} onChange={this.handleChange} />
);
}
}
Więcej szczegółów: https://typeofweb.com/2018/03/06/formularze-react-js-kontrolowane-komponenty/
Kompletny przykład:
import React, { Component } from 'react';
function validate(email, password) {
return {
email: email.length === 0,
password: password.length === 0,
};
}
class SignUpForm extends React.Component {
constructor(props) {
super();
this.state = {
email: '',
password: '',
everFocusedEmail: false,
everFocusedPassword: false,
inFocus: '',
};
}
handleEmailChange = (evt) => {
this.setState({ email: evt.target.value });
}
handlePasswordChange = (evt) => {
this.setState({ password: evt.target.value });
}
handleSubmit = (evt) => {
const errors = validate(this.state.email, this.state.password);
const isDisabled = Object.keys(errors).some(x => errors[x]);
if (isDisabled) {
evt.preventDefault();
return;
}
const { email, password } = this.state;
alert(`Login with email: ${email} password: ${password}`);
}
render() {
const errors = validate(this.state.email, this.state.password);
const isDisabled = Object.keys(errors).some(x => errors[x]);
return (
<form onSubmit={this.handleSubmit}>
<input
className={errors.email ? "error" : ""}
type="text"
placeholder="Enter email"
value={this.state.email}
onChange={this.handleEmailChange}
/>
<input
className={errors.password ? "error" : ""}
type="password"
placeholder="Enter password"
value={this.state.password}
onChange={this.handlePasswordChange}
/>
<button disabled={isDisabled}>Sign up</button>
</form>
)
}
}
export default SignUpForm;
Zobacz przykład [025]
Dodatkowe informacje:
- http://www.w3big.com/pl/react/react-forms-events.html
- http://software.es.net/react-dynamic-forms/#/
- https://goshakkk.name/the-missing-forms-handbook-of-react/
- https://goshakkk.name/array-form-inputs/
- https://goshakkk.name/on-forms-react/
- https://codeburst.io/reactjs-a-quick-tutorial-to-build-dynamic-json-based-form-a4768b3151c0
- http://appliedmathematicsanu.github.io/plexus-form/