reactで入力欄の値を取得する方法は何ですか?
入力フィールドの値を取得するには、Reactの制御されたコンポーネントを使用することができます。まず、コンポーネントのstateに入力フィールドの値を格納する変数を定義します。例えば:
constructor(props) {
super(props);
this.state = {
inputValue: ”
};
}
次に、入力欄の要素にonChangeイベントハンドラーを追加し、そのハンドラーでstate内のinputValueを更新する。例えば、
handleChange(event) {
this.setState({inputValue: event.target.value});
}
それから、renderメソッド内で入力ボックスの値をstate内のinputValueにバインドし、onChangeイベント処理関数を入力ボックスにバインドする。例えば:
render() {
return (
<input type=”text”
value={this.state.inputValue}
onChange={this.handleChange.bind(this)}
/>
);}
最後に、イベント処理関数内でstateのinputValueにアクセスして入力ボックスの値を取得することができます。例えば:
handleClick() {
console.log(this.state.inputValue);
}
したがって、ユーザーがコンテンツを入力すると、入力ボックスの値はコンポーネントのstateに保存され、stateにアクセスして入力ボックスの値を取得することができます。