为了账号安全,请及时绑定邮箱和手机立即绑定

使用map()方法创建的数组的索引

使用map()方法创建的数组的索引

慕姐8265434 2023-09-28 09:43:09
我正在使用 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>    );  }}
查看完整描述

2 回答

?
蛊毒传说

TA贡献1895条经验 获得超3个赞

输出:

https://i.stack.imgur.com/xloeO.gif

完整示例:


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


查看完整回答
反对 回复 2023-09-28
?
波斯汪

TA贡献1811条经验 获得超4个赞

您可以在函数内添加onClick一个,如下所示limap


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>

    );

  }


查看完整回答
反对 回复 2023-09-28
  • 2 回答
  • 0 关注
  • 62 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信