我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;
🍩 为答案点赞哈哈
最佳答案
虽然这不是一个非常可靠的解决方案,但假设 input
'name' 属性始终与您所在状态中的对象键完全匹配,您可以这样做:
handleNestedChange(e) {
const newStateContent = this.state.content;
newStateContent[e.target.id][e.target.name] = e.target.value;
this.setState({
content: newStateContent
});
}
关于javascript - react 嵌套的动态表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44929930/