Forms
“controlled components”と言われる方法で管理するのがスタンダード
Controlled Components
stateプロパティで状態を維持し、setStateで状態を変更する
Reactのstateは“single source of truth”
Reactによって“controlled component”と言われる方法で入力フォームを管理する
code:JavaScript
class NameForm extends React.Component {
constructor(props) {
super(props);
this.state = {value: ''};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event) {
this.setState({value: event.target.value});
}
handleSubmit(event) {
alert('A name was submitted: ' + this.state.value);
event.preventDefault();
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<label>
Name:
<input type="text" value={this.state.value} onChange={this.handleChange} />
</label>
<input type="submit" value="Submit" />
</form>
);
}
}
The textarea Tag
Reactではchildrenではなく、value属性でtextareaの値を扱う
The select Tag
selected属性の代わりにselectタグのvalue属性を使う
複数選択のselectタグを使用したい場合は以下のようにする
code:JavaScript
<select multiple={true} value={'B', 'C'}> The file input Tag
valueがReadonlyのため、uncontrolled componentである
Handling Multiple Inputs
name属性で識別してそれぞれの値変更イベントを処理する
code:JavaScript
handleInputChange(event) {
const target = event.target;
const value = target.type === "checkbox" ? target.checked : target.value;
const name = target.name;
this.setState({
name: value // ES6のcomputed property names });
}
Controlled Input Null Value
controlled componentのvalueプロパティにバインドすることで、ユーザーは入力値を変更できなくなる
valueを指定したけど変更可能な場合、undefinedやnullになる可能性がある
code:JavaScript
ReactDOM.render(<input value="hi" />, mountNode);
setTimeout(function() {
ReactDOM.render(<input value={null} />, mountNode);
}, 1000); // 1秒後に入力値が変更可能になる
Alternatives to Controlled Components
いちいち変更のイベントハンドラを定義したくない場合など
Fully-Fledged Solutions
バリデーションやtouchedフィールド判定、Submitのハンドリングなどのライブラリ
だけど、基本的にcontrolled componentとstate管理の原則は変わらないので、それらをしっかり理解しておくこと