[英]Adding component to React.js
import field from './Field.js'
classFieldSection extends Component{
render() {
return (
<div id="fieldSection">
<div id="fieldContent">
<label> Fields </label>
<Field />
</div>
</div>
<div>
<button> Add </button>
</div>
)
}
}
--Field.js--
<div>
<label>Test</label>
<input type="text" />
</div>
I am trying to keep adding under the existing on the button click.我试图在现有的按钮点击下继续添加。 Every time the button clicks, a new field needs to be created under it.
每次单击按钮时,都需要在其下创建一个新字段。
It cannot use the DOM.render as I get an error telling me to edit the status rather than use DOM.它不能使用 DOM.render,因为我收到一个错误,告诉我编辑状态而不是使用 DOM。
I tried:我试过:
/*class FieldSection extends Component{
25 constructor(){
26 super();
27 this.state = {
28 fields: [<Field />]
29 }
30 this.handleClick = this.handleClick.bind(this);
31 }
32
33 handleclick() {
34 var array = fields;
35 this.setState(prevState=> {
36 return {
37
38 }
39 }
40 }
41 render () {
42 return (
43 <div>
44 {this.state.fields.map(field => <Field {...field}/>)}
45 <div id="fieldButtons">
46 <button id="addField" type="button" onclick={this.handleClick})
47 > Add Field </button>
48 <button id="removeField" type="button"> Remove Field </button>
49 </div>
50 </div>
51 )
52 }
53 }*/
Thanks for providing your code.感谢您提供您的代码。 You've almost done it (except some syntaxes errors).
你几乎已经完成了(除了一些语法错误)。
First, initialize state.fields
with []
首先,用
[]
初始化state.fields
this.state = {
fields: []
}
Remove extra-parenthesis line 46 after onclick={this.handleClick}
在
onclick={this.handleClick}
之后删除额外的括号行 46
Choose between handleclick
or handleClick
.在
handleclick
或handleClick
之间handleclick
选择。 Your code got the both.你的代码得到了两者。
Then, in your handleClick
method, to push a element at the end of an array, do :然后,在您的
handleClick
方法中,要在数组末尾推送一个元素,请执行以下操作:
this.setState(prevState => ({
fields: [...prevState.fields, newElement]
}))
Hope this helps, good luck.希望这有帮助,祝你好运。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.