我有一个JSON
包含多个类别的文件,每个类别都有一个名称,其中包含一组具有自己名称和值的输入字段。
如何使用setState
来更新每个的值字段onChange
?类别和字段使用map()
.
我可以在没有嵌套字段的情况下使其工作,但不能使用。感谢任何帮助。
JSON 文件
[{
"catName": "Category 1",
"fields": [
{
"name": "field 1",
"amount": "0"
},
{
"name": "field 2",
"amount": "0"
}
]
},
{
"catName": "Category 2",
"fields": [
{
"name": "field 1",
"amount": "0"
},
{
"name": "field 2",
"amount": "0"
}
}]
主程序
import React, { Component } from "react";
import Category from "./Category";
import sampleData from "./sampleData";
class Main extends Component {
constructor(props) {
super(props);
this.state = {
list: sampleData
};
}
handleChange = e => {
this.setState({ ??? });
};
render() {
return (
<div>
{this.state.list.map(item => (
<Category
id={item.catName}
name={item.catName}
key={item.catName}
list={item}
handleChange={this.handleChange}
/>
))}
</div>
);
}
}
export default Main;
分类.js
import React from "react";
import Item from "./Item";
const Category = ({ name, list, handleChange }) => {
return (
<div className="section">
<h3>{name}</h3>
{list.fields.map(item => (
<Item
id={item.name}
name={item.name}
key={item.name}
list={item}
handleChange={handleChange}
/>
))}
</div>
);
};
export default Category;
项目.js
import React from "react";
const Item = ({ list, handleChange }) => {
return (
<div className="item">
<label className="label">{list.name}</label>
<input
name={list.name}
id={list.name}
className="input"
type="text"
onChange={handleChange}
value={list.amount}
/>
</div>
);
};
export default Item;