React.js引导添加或删除输入字段

React.js Bootstrap Add or Remove Input Fields

本文关键字:删除 输入 字段 添加 js React      更新时间:2023-09-26

我正在使用React.jsreact-bootstrap构建一个web应用程序。我有一个表单页面,用户可以在其中输入他们正在经历的疾病的症状。我希望用户能够键入文本,还可以选择删除以前键入的文本。

下面是用Javascript实现的示例:http://bootsnipp.com/snippets/featured/dynamic-form-fields-add-amp-remove-bs3

我希望拥有与上面链接相同的功能,但使用React。这是我到目前为止为本节编写的代码,但我不确定继续的最佳方式。

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>

调用this.addSymptomField()时,我希望向页面添加一个Input字段,调用this.removeSymptomField()时,我想从页面中删除现有的Input字段。

非常感谢!

您可以保持当前输入的状态列表,并在调用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方法

时,只需在列表中添加或删除输入即可