reactjs - 在 React 组件中如何索引嵌套数组?
问题描述
在构建一个表单时,用户输入一组由一组属性评估的项目的数字评级时,我如何相应地设置它们的索引以及捕获/更新状态中所有输入以便我可以比较的最佳方法是什么他们总以后?代码可以在下面或沙箱中找到感谢您的任何输入。
import React, { Component } from "react";
export default class Compare extends Component {
constructor(props) {
super(props);
this.state = {
items: props.items,
attributes: props.attributes,
itemAttributeScoreArray: [],
eval: null
};
}
_onChangefor = (index1, index2) => event => {
console.log(event.target.value);
};
render() {
return (
<div>
<table
className="Table"
style={{
margin: "0 auto"
}}
>
<thead>
<tr>
<th>Compare</th>
<th>{this.state.items[0]}</th>
<th>{this.state.items[1]}</th>
</tr>
</thead>
<tbody>
{this.state.attributes.map((attribute, index1) => (
<tr>
{attribute}
{this.state.items.map((item, index2) =>
<td>
<input
key = {index1+''+index2}
type="number"
onChange={this._onChangefor((index1, index2))}
/>
</td>)}
</tr>
))}
</tbody>
</table>
</div>
);
}
}
解决方案
您可以假设属性和项目是保存主数据的状态,因此您需要一个事务状态来保存您的事务,所以我尝试添加一个名为“事务”的状态来保存您的输入值,
constructor(props) {
super(props);
this.state = {
items: props.items,
attributes: props.attributes,
itemAttributeScoreArray: [],
eval: null,
transaction: []
};}
然后在 componentDidMount 上为交易添加价值,
componentDidMount(){
let transaction = [];
this.props.attributes.map((attr,idx) =>{
let _attributes = { attribute: attr, item:[] }
this.props.items.map((_attr,_idx) =>{
let _temp = _attr;
_attributes.item.push({name: _attr, value: 0});
})
transaction.push(_attributes);
})
this.setState({transaction: transaction})}
那么你可以像这样呈现你的输入
<tbody>
{this.state.transaction.map((attribute, index1) => (
<tr>
{attribute.attribute}
{attribute.item.map((item, index2) =>
<td>
<input
key = {index1+''+index2}
type="number"
value={item.value}
onChange={this._onChangefor(attribute.attribute, index2)}
/>
</td>)}
</tr>
))}
</tbody>
最后一件事是您需要将输入的值作为_onChangefor 中的交易值处理
_onChangefor = (index1, index2) => event => {
let _val = event.target.value;
this.setState(
state => {
const list = this.state.transaction.find(result => result.attribute === index1).item.map((items, j) => {
if (j === index2) {
items.value = _val;
return items;
} else {
return items;
}
});
return {
list,
};
}
);};
就是这样,如果您还有任何问题,请告诉我,(y)
推荐阅读
- delphi - TRelativePanel 循环依赖
- vue.js - 无论如何在过渡结束时保持显示块?
- java - org.sqlite.SQLiteException: [SQLITE_ERROR] SQL 错误或缺少数据库(没有这样的表:帐户)
- react-hook-form - 获取未捕获的类型错误:path.split 不是反应中的函数
- c++ - 错误地使用指针/引用?
- godot - 通过 Godot 中的嵌套函数传递变量的正确方法是什么?
- bash - bash脚本未执行
- python - 多服务器套接字条件
- swiftui - SwiftUI SpriteView 问题 - 停止添加节点
- python - 烧瓶网络服务器 | 停止 python 脚本会导致崩溃