我一直试图用React和Meteor创建一个动态表单,但遇到了问题。
这是我的表格:
appendInput() {
var newInput = `input-${this.state.inputs.length}`;
console.log (newInput);
this.setState({ inputs: this.state.inputs.concat([newInput]) });
}
render() {
return (
<div className="background-container">
<form ref={(input) => this.sparkForm = input} onSubmit={(e) => this.createSpark(e)}>
<ControlLabel>Select your person (optional)</ControlLabel>
<select id="formControlsPerson" placeholder="Choose your person" className="form-control" ref={(input) => this.person = input}>
<option value='select'>Select your person</option>
<option value='jane'>Jane Siesta</option>
<option value='ben'>Ben Huang</option>
<option value='han'>Han Han</option>
<option value='mau'>Mau Mau</option>
<option value='void'>VOID</option>
<option value='tommy'>Tommy Hendriks</option>
<option value='gareth'>Gareth Williams</option>
<option value='gigi'>Gigi Lee</option>
</select>
<ControlLabel>Select your location (optional)</ControlLabel>
<select id="formControlsLocation" placeholder="Choose your location" className="form-control" ref={(input) => this.location = input}>
<option value='select'>Select your location</option>
<option value='shelter'>Shelter</option>
<option value='mansion'>The Mansion</option>
</select>
<ControlLabel>Title</ControlLabel>
<input type="text" label="Title" placeholder="Enter your title" className="form-control" ref={(input) => this.title = input}/>
<ControlLabel>Add Image</ControlLabel>
<div className="upload-area">
<p className="alert alert-success text-center">
<span>Click or Drag an Image Here to Upload</span>
<input type="file" id="input" className="file_bag" onChange={this.upload} />
</p>
</div>
<ControlLabel>Content</ControlLabel>
<div className='_quill'>
<ReactQuill
toolbar={false}
theme="snow"
ref='editor'
onChange={this.onChange}
events={events} />
</div>
<br />
<ControlLabel>Media (optional)</ControlLabel>
<div id="dynamicInput">
{this.state.inputs.map(input => <input key={input} type="text" label="Media" placeholder="Add your media url" className="form-control" ref={(input) => this.mediaUrl = input}/> )}
</div>
<Button onClick={ () => this.appendInput() }>
Add media field
</Button>
<Button type="submit" data-dismiss="modal">Submit</Button>
我可以使用您在上面看到的功能向表单添加一个额外的字段。我现在有两个问题。
我如何从添加的字段中获取值?我可以从我用来从普通输入字段获取它的方式获取第一个函数的值,但当然这不适用于其他添加的字段。我不知道如何解决这个问题。
如何删除添加的字段?
希望有人可以帮我完成这个!
答案 0 :(得分:0)
将this.mediaUrl
更改为this.mediaUrls
(数组)并循环显示以获取值
你这样做会导致this.mediaUrl只有最后一个输入的值。由于有多个输入,您需要跟踪所有输入。
{this.state.inputs.map((input, idx) => <input key={input} type="text" label="Media" placeholder="Add your media url" className="form-control" ref={(input) => this.mediaUrls[idx] = input}/> )}