我 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;
&amp;赞美答案哈哈
答案 0 :(得分:1)
虽然它不是一个非常强大的解决方案,但假设input
'name'属性始终与您所在州的对象键完全匹配,您可以这样做:
handleNestedChange(e) {
const newStateContent = this.state.content;
newStateContent[e.target.id][e.target.name] = e.target.value;
this.setState({
content: newStateContent
});
}
答案 1 :(得分:0)
我认为handleNestedChange
没有正确绑定,因为上下文this
引用的是map函数而不是组件。您必须将map函数与当前上下文绑定。
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>
)
}).bind(this)