2016-03-01 24 views
1

我有一個React組件,它有幾個簡單的輸入字段,我目前正在跟蹤最終放入AJAX調用的狀態。我也有一個按鈕,點擊後,會創建一個新的輸入字段行(與初始輸入相同)。在React中添加組件和跟蹤狀態的新輸入

我是React的新手,最初構建了一個簡單的函數來克隆整個div並將其附加到.ticket-section div。我遇到了一些關於具有相同react-id的輸入的問題,並且誠實地感覺到我正在與框架進行一點對抗。

有關如何創建這些新輸入並能夠單獨跟蹤新一行輸入的狀態的任何建議?提前非常感謝。

這裏是我的組件:再次

var AddItem = React.createClass({ 
    getInitialState: function() { 
    return {item_name: '', quantity: '', price: ''} 
    }, 
    itemNameChange: function(e) { 
    this.setState({item_name: e.target.value}); 
    }, 
    quantityChange: function(e) { 
    this.setState({quantity: e.target.value}); 
    }, 
    priceChange: function(e) { 
    this.setState({price: e.target.value}); 
    }, 
    render: function() { 
    return (
     <div> 
     <div className="ticket-section"> 
     <div className="add-ticket"> 
      <ul> 
      <li> 
       <label>Name</label> 
       <input id="item-name" type="text" placeholder="xyz item" value={this.state.item_name} onChange={this.itemNameChange} /> 
      </li> 
      <li> 
       <label>Quantity Available</label> 
       <input id="quantity" type="number" placeholder="100" value={this.state.quantity} onChange={this.quantityChange} /> 
      </li> 
      <li> 
       <label>Price</label> 
       <input id="price" type="number" placeholder="25.00" value={this.state.price} onChange={this.priceChange} /> 
      </li> 
      </ul> 
     </div> 
     </div> 
     <button className="add-another-item">+ Add another item</button> 
     </div> 
    ); 
    } 
}); 

感謝。

回答

2

我不確定,但讓我qu,,你​​在找這樣的東西嗎?

class InputComponent extends React.Component { 
    constructor(props){ 
    super(props) 
    } 
    render(){ 
    return <div> 
     <input type="text" 
     onChange={this.props.change}/> 
    </div> 
    } 
} 

class Widget extends React.Component { 
    constructor(){ 
    this.state = { 
     values: [''] 
    }; 
    this.handleClick = this.handleClick.bind(this); 
    } 
    handleChange(index, e){ 
    const oldState = this.state.values; 
    oldState[index] = e.target.value 
    this.setState({values: oldState}) 
    } 

    handleClick(){ 
    const oldState = this.state.values 
    oldState.push(''); 
    this.setState({values: oldState}) 
    } 
    render(){ 
    const itemList = this.state.values.map((item, index)=>{ 
     return <InputComponent key={index} change={this.handleChange.bind(this, index)}/> 
    }); 
    console.log(this.state.values) 
    return <div> 
     {itemList} 
     <hr/> 
     <button onClick={this.handleClick}>Click</button> 
    </div> 
    } 
} 

React.render(<Widget />, document.getElementById('container')); 

Fiddle example.我希望它能幫助你。

謝謝

+0

感謝您的支持!不完全是我需要的,但絕對是我可以參考的東西。 – luke

+0

@luke您好! –