我是soooo接近讓這個工作,但似乎無法包裹我的頭圍繞此。反應嵌套的動態表格
我有一個是應該提交給JSON文件結構如下形式:
{
title: '',
content: [
{className: '', body: ''}
]
}
我能夠設置狀態爲標題沒有問題的,以及在第一個對象內容數組。我想我需要創建一個循環或什麼?以下是我的完整組件。
import React, { Component } from 'react';
class AddEditPage extends Component {
constructor(props) {
super(props)
this.state = {
title: '',
content: [
{className: '', body: ''}
]
}
this.addInput = this.addInput.bind(this);
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
this.handleNestedChange = this.handleNestedChange.bind(this);
}
handleChange(e) {
const value = e.target.value
this.setState({
[e.target.name]: value
})
}
handleNestedChange(e) {
const value = e.target.value
console.log(e.target.id)
this.setState({
})
}
handleSubmit(e) {
e.preventDefault();
console.log(this.state)
}
addInput() {
const newInput = { className: '', body: ''}
this.setState({content: this.state.content.concat(newInput)});
}
render() {
const contentInputs = this.state.content.map((content, i)=> {
return (
<div key={i}>
<input
type="text"
name="className"
id={`${i}`}
placeholder="Class name"
onChange={this.handleNestedChange}
/>
<input
type="text"
name="body"
placeholder="Body"
id={`${i}`}
onChange={this.handleNestedChange}
/>
</div>
)
})
return (
<div>
<h2>New Page</h2>
<form onSubmit={this.handleSubmit}>
<input
type="text"
name="title"
placeholder={this.state.title || `Enter the title`}
onChange={this.handleChange}
/>
<h3>Content</h3>
{contentInputs}
<button onClick={this.addInput}>Add</button>
<input type="submit" />
</form>
</div>
);
}
}
export default AddEditPage;
&好評的答案哈哈
你的問題到底是什麼?有一點需要注意的是你有addInput的方式,state.content永遠不會增長(我相信)。嘗試使用push來代替,即讓newValues = this.state.content.push(newInput),然後this.setState({content:newValues}); – terpinmd
@terpinmd添加輸入工作很好。它設置嵌套輸入的狀態部分,即時通訊與 – Dileet