首页 > 解决方案 > 使用 map() 方法创建的数组的索引

问题描述

我正在使用 React .js 有 3 个数组a, b, c。我使用该方法将数组添加a到 HTML 标记。map()我需要:

  1. onClick将事件处理程序挂在a数组的元素上,以便在单击元素时,将此元素反映到<List />组件中。

  2. <List />组件应显示数组的元素,bc具有与按下的数组元素的索引相同的索引a
    例如:在 HTML 标记中,我单击“plum”元素(索引 = 2)。在<List />组件中,您需要获取“plum”和元素“Sophie”和“audi”(索引 = 2 个数组bc

以上几点怎么办?

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>
    );
  }
}

标签: javascriptreactjs

解决方案


输出:

在此处输入图像描述

完整示例:

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


推荐阅读