如何在单击按钮上添加动态表单?

时间:2017-08-22 07:03:00

标签: reactjs

我正在制作一个反应应用,我需要在点击按钮时添加表单。目前我正在通过增加一个计数器并根据柜台号码显示表格来做。但我需要提交所有表格并获得单击按钮的数据,但我已经提交了每个表格,并获得了该特定表格的数据。如何解决这个问题?

这就是我展示表格的方式:

var HocAddForm = function(AbstractComponent,title){
return class extends React.Component {
constructor(props){
  super(props);
  this.state={
    anotherForm:1
  }
  this.newForm=this.newForm.bind(this);
}
newForm(){
  this.setState({
    anotherForm:this.state.anotherForm+1
  })
}
displayForm(){
   let forms = [];
   for(let i = 0; i < this.state.anotherForm; i++){
     forms.push(
     <div key={i}>
         <AbstractComponent/>
     </div>
    )
   }
   console.log(this.state.value);
   return forms || null;
}

render() {
  const anotherForm=this.state.anotherForm;
  const heading=title;
  return(
    <div>
      <button id="add-button" onClick={this.newForm}>AddForm</button>
      <h3 className="form-place">{heading}</h3>
      {this.displayForm()}
    </div>
  )
}
}
}

我的AbstractComponent是:

class Experiance extends Component {
    render() {
        return (
            <Form onSubmit={this.props.onSubmit}>
                <fieldset disabled={this.props.disabled}>
                    <Input
                        type="text"
                        name="companyName"
                        title="Company Name"
                        value=""
                    />
                    <Input
                        type="number"
                        name="experiance"
                        title="No.of Years Worked"
                        value=""
                    />
                </fieldset>
                <button id="button-right">
                    {this.props.buttonName}
                </button>
            </Form>
        );
    }
}

1 个答案:

答案 0 :(得分:0)

在这种情况下,我会使用状态,将表单保存为节点数组,单击“将新组件添加到数组”,然后渲染到数组上的简单映射

伪代码:

state = {
 forms: []
}

onClickMethod () => {
 this.setState(state=> state.forms.push(<Experience />))
}

render() {
 return (
  ...
  <form className="forms" onSubmit={this.onSubmit}> //your container
   this.state.forms.map(item => <item />)
  </form>
 )
}