2017-09-13 10 views
2

入力要素の値を変数に代入する必要があります。フォームには、それぞれ固有のIDと入力IDと同じ名前の変数が同じ10個の入力があります。すべての入力に機能saveChanges()を割り当てonChangeは、クラス属性、この上の任意の提案は参考になる本反応名で変数を取得する

class MainClass extends React.Component { 
    render() { 
     var field1 = ""; 
     var field2 = ""; 
     var date1 = ""; 
     var description = ""; 
     //... 
     function saveChanges() { 
      document.getElementsByClassName("inputs").onchange = function (event) { 
       // tried to use window["variable name"] to access the variables but page broke and goes into repetitive reload 
       // need to know that is there any other method to save the changed value to respective variable 
       window[event.target.id] = event.target.value; 
      } 
     } 
     function sendDetails() { 
      // use the values of the variables and send through rest api 
     } 
     return (
      <div> 
       lable1: 
       <input id="field1" className="inputs" type="text" onChange={saveChanges } /><br /> 
       lable2: 
       <input id="field2" className="inputs" type="text" onChange={saveChanges } /><br /> 
       date1: 
       <input id="date1" className="inputs" type="text" onChange={saveChanges } /><br /> 
       Description: 
       <textarea id="discription" className="inputs" onChange={saveChanges }> 
       </textarea> 
       //... 
       <button id="sendDetails" onClick={sendDetails }> 
        Send 
       </button> 
      </div> 
     ); 
    } 
} 

のようになります。

+0

あなたは私の答えを見たことがありますか? – Andrew

答えて

0

あなたの入力に名前を付け、そしてevent.target.nameとそれへのアクセスを得ることができます。

class MainClass extends React.Component { 
    render() { 
     var field1 = ""; 
     var field2 = ""; 
     var date1 = ""; 
     var description = ""; 
     //... 
     function saveChanges(e) { 
      this.setState({[e.target.name]: e.target.value}); 
     } 
     function sendDetails() { 
      // use the values of the variables and send through rest api 
      console.log(this.state); 
     } 
     return (
      <div> 
       lable1: 
       <input id="field1" name="field1" className="inputs" type="text" onChange={saveChanges } /><br /> 
       lable2: 
       <input id="field2" name="field2" className="inputs" type="text" onChange={saveChanges } /><br /> 
       date1: 
       <input id="date1" name="date1" className="inputs" type="text" onChange={saveChanges } /><br /> 
       Description: 
       <textarea id="discription" className="inputs" onChange={saveChanges }> 
       </textarea> 
       //... 
       <button id="sendDetails" onClick={sendDetails }> 
        Send 
       </button> 
      </div> 
     ); 
    } 
} 
+0

でもevent.target.idはid値を返し、別の属性 'name'を使用する目的は何ですか? –

+0

状態を設定するための提案は、変数を設定することを検討していたので非常に役に立ちます –

関連する問題