2017-03-28 3 views
0

フォームのすべての入力フィールドの状態を変更する3つの関数を記述する必要があります。電話やアドレスなどのフィールドがさらにある場合は、さらに2つの関数これらのフィールドの状態を変更するには、フォームフィールドごとに別々の関数を書くのではなく、このフォームのフィールドの状態を変更するための汎用関数を書くことしかできないのですか?あなたがそのようなhandleChangeを使用フォームフィールドの状態を設定する汎用イベントハンドラ

handleChange = (type, event) => { 
    this.setState({[type]: event.target.value}); 
} 

class SignUpForm extends React.Component { 
     constructor() { 
      super(); 
      this.state = { 
       name: '', 
       email: '', 
       password: '', 

      }; 
     } 

     handleNameChange = (evt) => { 
      this.setState({name: evt.target.value}); 
     } 

     handleEmailChange = (evt) => { 
      this.setState({email: evt.target.value}); 
     } 

     handlePasswordChange = (evt) => { 
      this.setState({password: evt.target.value}); 
     } 
     render(){ 
      return(
       <form onSubmit={this.handleSubmit}> 
        <input 
         type="text" 
         placeholder="Enter Name" 
         value={this.state.name} 
         onChange={this.handleNameChange} 
        /> 
        <input 
         type="text" 
         placeholder="Enter email" 
         value={this.state.email} 
         onChange={this.handleEmailChange} 
        /> 
        <input 
         type="password" 
         placeholder="Enter password" 
         value={this.state.password} 
         onChange={this.handlePasswordChange} 
        /> 
        <button disabled={isDisabled}>Sign up</button> 
       </form> 
      ) 
     } 

    } 

答えて

2

次のパターンを使用することができ

<input 
    type="text" 
    placeholder="Enter Name" 
    value={this.state.name} 
    onChange={(event) => this.handleChange('name', event)} 
/> 
+0

はそれに私を打ちます。この[回答は関連している](http://stackoverflow.com/questions/2462800/how-do-i-create-a-dynamic-key-to-be-added-to-a-javascript-object-variable) –

関連する問題