2016-03-27 66 views
1

我正在使用React.jsreact-bootstrap構建Web應用程序。我有一個表單頁面,用戶可以輸入他們正在經歷的疾病症狀。我希望用戶能夠鍵入文本,並且還可以選擇刪除以前輸入的文本。React.js Bootstrap添加或刪除輸入字段

在Javascript中正在做它的一個例子是在這裏: http://bootsnipp.com/snippets/featured/dynamic-form-fields-add-amp-remove-bs3

我想有相同的特徵,因爲上面的鏈接,但使用反應。以下是該部分迄今爲止的代碼,但我不確定繼續的最佳方式。

var closeButton = <Button onClick={this.removeSymptomField()}>Close</Button>; 

<Input type="text" buttonAfter={closeButton} placeholder="Type a symptom here."/> 

<Button onClick={this.addSymptomField()}>Click to add a new symptom.</Button> 

當​​被調用時,我想的Input字段添加到頁面,當this.removeSymptomField()叫,我想從頁面移除現有Input領域。

非常感謝!

回答

1

你可以保持當前的輸入列表中的狀態和修改調用addSymptomFieldremoveSymptomField

時,在你的組件構造

this.state = { inputs: [] } 

在渲染

<div className="inputs"> 
    {this.renderInputs()} 
</div> 

和你renderInputs方法可能看起來像這樣

renderInputs() { 
    return this.state.inputs.map((input, index) => <Input key={index} type="text" buttonAfter={closeButton} placeholder="Type a symptom here."/>) 
} 

然後簡單地添加或致電addSymptomFieldremoveSymptomField方法

+0

這是偉大的,非常輕便,當從列表中刪除輸入/,太感謝你了! –

+0

我知道如何添加按鈕功能。 但如何將刪除功能樣子,如果這是我的外接場函數: appendInput(){VAR = newInput'輸入 - $ {this.state.inputs.length}'; this.setState({inputs:this.state.inputs.concat([newInput])}); } – Deelux