动态添加输入表单字段问题reactjs

时间:2019-01-02 14:18:02

标签: javascript reactjs

我正在尝试通过单击按钮 +添加内容动态添加一个层叠的表单(内部)字段。该字段的数组正在更新,但视图仍然相同。

但是,当我尝试单击按钮 + Add Heading 来动态添加外部字段时,它的添加没有问题。 以下是stackblitz网址,以供参考。预先感谢。

https://stackblitz.com/edit/react-utjwsu?embed=1&file=index.js

3 个答案:

答案 0 :(得分:1)

您只会渲染一个“内容”字段,而{this.AddContentInput}是无效的语法。您可以编辑AddContentBox方法以呈现所有“内容”字段:

原文:

...
<FormGroup>
    <Label className="set-label-pos upload-img" for="Heading">Content</Label>
    <input className="form-control" type="text"/>
</FormGroup>
{this.AddContentInput}
...

替换为:

...
{ this.AddContentFields(element) }
...

AddContentFields(element) {
  return element.Content.map(content => {
    return (
      <FormGroup>
        <Label className="set-label-pos upload-img" for="Heading">Content</Label>
          <input className="form-control" type="text"/>
        </FormGroup>
    );
  })
}

这是应用程序的编辑版本,其中包含我的更改:https://stackblitz.com/edit/react-lcy2te

答案 1 :(得分:1)

您的代码运行正常,状态正在完美更新。问题是Content部分仅在您的代码中添加一次。我只是使用了已经在其中添加的功能

{this.addContentTextBox(element.Content)}

只需将AddContentBox函数替换为此:

AddContentBox(){
        return this.state.content.map((element,i)=>(
            <div className="header-content" key={i} >
                <div className="heading-content-wrapper">
                <FormGroup>
                <Label className="set-label-pos upload-img" for="Heading">Heading</Label>
                <input className="form-control" type="text"/>
                </FormGroup>
                {this.addContentTextBox(element.Content)}
                {this.AddContentInput}
                <FormGroup>
                <Button color="success" onClick={this.AddContentInput.bind(this,i)}>+ Add Content</Button>
                </FormGroup>
            </div>
            </div>
        ))
    }

您在该文件中有代码,但是我认为您忘记将其添加到函数中。

希望它会有所帮助:)

答案 2 :(得分:0)

您正在混合content变量。在函数AddContentBox()中,您正在使用this.state.content.map(...)

this.state.content{Heading: '', Content: [{value: ''}]}

之类的对象数组

在您的函数AddContentInput()中正在将对象推入此数组contents[index].Content.push({value:''})

的对象内

根据您的需要,您应该压入根数组contents.push({Heading: '', Content: [{value: ''}]} 在函数AddContentBox()中迭代正确的数组并使用this.state.content[0].Content.map(...)

相关问题