2017-01-22 38 views
0

對於reactjs和JavaScript,所有東西都還是新手,所以這可能很簡單,但我還沒有找到一個在線搜索的例子。如何使用onClick在同一行中獲取輸入數據 - reactjs

我想建立一個表,每一行都有一個輸入框和一個onClick /提交,然後發送該函數中該行輸入的輸入量,或者以某種方式訪問​​該行的輸入數據。行是從保存狀態的數組構建的。

這裏是我目前所處位置的精簡代碼。這只是被更高級別的容器調用的表,它會傳遞biweeklyPays和saveChanges。

function PayoutsTable(props) { 
    var payoutRows = [] 
    var biweeklyPays = props.biweeklyPays 
    for (let b of biweeklyPays) { 
     payoutRows.push(
      <tr> 
       <td>{b.user.first_name + ' ' + b.user.last_name}</td> 
       <td>{b.biweeklyPay.payoutAmount}</td> 
       <td><input className="form-control" type="number" id="payoutAmount" step=".01" min="0" /></td> 
       <td><button className="btn btn-primary" onClick={() => props.saveChanges(b)}>Submit</button></td> 
      </tr> 
     ) 
    } 
    return (
     <div> 
      <table className="table table-responsive table-striped"> 
       <thead> 
        <tr> 
         <th>Name</th> 
         <th>Payout Amount</th> 
         <th></th> 
         <th></th> 
        </tr> 
       </thead> 
       <tbody> 
        {payoutRows} 
       </tbody> 
      </table> 
     </div> 
    ) 
} 

回答

0

你所創建的是通過定義不能用於有狀態的「解決方案」編輯等輸入或其他形式的純粹的,無狀態的組件。

您應該將組件轉換爲類state,並在輸入值更改時更新狀態。

步驟:

  1. 轉換爲類(https://facebook.github.io/react/docs/state-and-lifecycle.html#converting-a-function-to-a-class
  2. 渲染輸入的實際值 - 在輸入的變化><input ... value={this.state.values[i]} .../>
  3. 寄存器 - > this.updateInput(I,E)}`
  4. 按鈕將發送本地狀態父 - ><button ... onClick={() => this.props.saveChanges(b, this.state.values[i])

i爲您的迭代的指數,你可以改變你for到例如_.forEach(biweeklyPays, (b, i) => { .... }

我假定你保持輸入值的數組中state,要做到這一點,你應該初始化您的組件是這樣的:

getInitialState: function() { 
    return { values: [] }; 
} 

提到的onUpdateRowValue(i, e)只需更新i狀態的第幾個元素:

onUpdateRowValue: function(i, e) { 
    var values = this.values.slice(0); 
    values[i] = e.target.value 
    this.setState({values: values}); 
} 
相關問題