[英]the index of the array created with the map() method
我正在使用 React.js 有 3 個 arrays a
, b
, c
。 我使用map()
方法將數組a
添加到 HTML 標記。 我需要:
將onClick
事件處理程序掛在a
數組的元素上,以便在單擊該元素時,將此元素反映到<List />
組件。
<List />
組件應顯示 arrays b
和c
的元素,其索引與按下的數組元素a
的索引相同。
例如:在 HTML 標記中,我單擊“梅花”元素(索引 = 2)。 在<List />
組件中,您需要獲取“plum”以及元素“Sophie”和“audi”(索引 = 2 arrays 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>
);
}
}
Output:
完整示例:
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
您可以在map
function 中的每個li
中添加一個onClick
,如下所示
itemsThatMatchIndex = []
getItemsInBAndCThatMatch(index) {
this.itemsThatMatchIndex = [this.b[index], this.c[index]];
}
render() {
let pp = this.a.map((arr, idx) => {
return (<li key={idx}>
<button onClick={() => this.getItemsInBAndCThatMatch(idx)}>
{this.a[idx]}
</button>
</li>);
});
return (
<div>
<div>
<ul>{pp}</ul>
</div>
<List data={this.itemsThatMatchIndex}/>
</div>
);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.