javascript - 使用 map() 方法创建的数组的索引
问题描述
我正在使用 React .js 有 3 个数组a
, b
, c
。我使用该方法将数组添加a
到 HTML 标记。map()
我需要:
onClick
将事件处理程序挂在a
数组的元素上,以便在单击元素时,将此元素反映到<List />
组件中。该
<List />
组件应显示数组的元素,b
并c
具有与按下的数组元素的索引相同的索引a
。
例如:在 HTML 标记中,我单击“plum”元素(索引 = 2)。在<List />
组件中,您需要获取“plum”和元素“Sophie”和“audi”(索引 = 2 个数组b
和c
)
以上几点怎么办?
export default class App extends Component {
a = ["Apple", "pear", "plum", "currant", "strawberry"];
b = ["Amelia", "Oliver", "Sophie", "Alfie", "Jacob"];
c = ["mercedes", "bmw", "audi", "volkswagen", "hyundai"];
render() {
let pp = this.a.map((arr, idx) => {
return <li key={idx}>{this.a[idx]}</li>;
});
return (
<div>
<div>
<ul>{pp}</ul>
</div>
<List />
</div>
);
}
}
解决方案
输出:
完整示例:
import React, { Component } from "react";
export default class App extends Component {
constructor(props) {
super(props);
this.state = {
a: ["Apple", "pear", "plum", "currant", "strawberry"],
b: ["Amelia", "Oliver", "Sophie", "Alfie", "Jacob"],
c: ["mercedes", "bmw", "audi", "volkswagen", "hyundai"],
index: null
};
}
setIndex = i => {
console.log(i);
this.setState({
index: i
});
console.log(this.state.index);
};
render() {
return (
<div>
{this.state.index !== null && (
<div>
<List
a={this.state.a[this.state.index]}
b={this.state.b[this.state.index]}
/>
</div>
)}
<div>
<ul>
{this.state.a.map((arr, idx) => (
<li
onClick={() => {
console.log("hi");
this.setIndex(idx);
}}
>
{arr}
</li>
))}
</ul>
</div>
</div>
);
}
}
class List extends Component {
constructor(props) {
super(props);
}
render() {
return (
<div>
<ul>
<li>{this.props.a}</li>
<li>{this.props.b}</li>
</ul>
</div>
);
}
}
您可以在此处查看工作示例:stackblitz
推荐阅读
- python - python给出的数组是一维的,但是有2个被索引错误
- python - Discord.py 检测嵌入标题或描述中的消息
- qt - 为什么 ScrollView 中的动态对象不会随其他内容滚动?
- reactjs - 即使在传递属性后,RenderLeader 组件也不会呈现
- python - NetworkX:如何构建 k-Partite Graph 图
- lua - 有没有提供 Roblox lua 语法高亮的 Monaco 编辑器?
- c# - DataGridView – 同一列/单元格中的字符串和小数
- swift - 无法证明 NSMutableAttributedString
- java - Log4J2 是否具有等效于 Log4J 的渲染器?
- reactjs - 无效的 Unicode 转义序列