2017-10-04 5 views
2

何が良いですか?リアクション - this.input.value対ハンドル変更

私は10入力のフォームを持っています。

this.input.valueを使用するか、変更を処理してstateに保存する必要がありますか?ドキュメントから

handleChange(e) { 
    this.setState({input: e.target.value}); 
} 
... 
<input type="text" value={this.state.input} onChange={this.handleChange} /> 

または

onSubmit() { 
    const inputValue = this.input.value; 
    ... 
} 
... 
<input type="text" ref={(input) => {this.input = input;}} /> 

制御入力を設定する参考文献

There are a few good use cases for refs: 

    Managing focus, text selection, or media playback. 
    Triggering imperative animations. 
    Integrating with third-party DOM libraries. 

Avoid using refs for anything that can be done declaratively. 
+0

まず、「this.input.value」は機能しません。 'this.refs'を使って入力ボックスを参照する必要があります。私は複雑さを回避するために状態を使用します –

+0

これは達成しようとしていることに依存します:入力ごとに行われるべきアクションがあるか、すべての値が提出された後、 –

+0

@TravelingTechGuy、もう1つ。 – Nick

答えて

3

を使用するための痛みのようなものが、私ですこのパターンを使うo少し楽にしてください。

は、すべての入力のための1つのonChangeイベントハンドラを作成します。次に

handleInputChange(e){ 
    const target = e.target; 
    const value = target.type === 'checkbox' ? target.checked : target.value; 
    const name = target.name; 
    this.setState({ 
     [name]: value 
    }); 
} 

を、あなたの入力のために、それを更新するために、あなたの状態でキーと一致nameを与えるようにしてください。

render() { 
    const { firstName, lastName, email, acceptTerms } = this.state; 
    return (
     <form> 
      <input name="firstName" onChange={this.handleInputChange} value={firstName} /> 
      <input name="lastName" onChange={this.handleInputChange} value={lastName} /> 
      <input name="email" onChange={this.handleInputChange} value={email} /> 
      <input type="checkbox" name="acceptTerms" onChange={this.handleInputChange} checked={acceptTerms} /> 
     </form> 
    ) 
} 
+0

よく見えます。私はあなたがファイル間でこの機能を再利用すると思います。 – nicooga

+0

ええ、私はそれをHOCに変換しようと考えていました。あまりにも多くをまだ実験していない。 –

+0

ええ、よく見えます。私の実際のプロジェクトでは、 'onChange = {this.handleInputChange.bind(null、 'name')}'と 'handleInputChange(inputName、e){this.setState({[inputName]:e.target.value})}}を実行します。 '。あなたのコードは良く見えます。しかし、私は例の中で 'this.input.value'をたくさん見て、私がそれを使用できるかどうか疑問に思います。 – Nick

関連する問題