简体   繁体   English

在 ReactJS 中,如何使用 map() 为每个项目创建下拉菜单?

[英]In ReactJS how can I use map() to create dropdown menus for each item?

I've been trying for hours to use map() in react to have each item in the iterable render a drop down list:我已经尝试了几个小时来使用map()来让可迭代中的每个项目呈现一个下拉列表:

import React, { Component } from 'react';

class Card extends Component {
  constructor(props) {
    super(props);

    this.state = {
      showMenu: false,
    };

    this.showMenu = this.showMenu.bind(this);
    this.closeMenu = this.closeMenu.bind(this);
  }

  showMenu(event) {
    event.preventDefault();

    this.setState({ showMenu: true }, () => {
      document.addEventListener('click', this.closeMenu);
    });
  }

  closeMenu(event) {

    if (!this.dropdownMenu.contains(event.target)) {

      this.setState({ showMenu: false }, () => {
        document.removeEventListener('click', this.closeMenu);
      }); 

    }
  }

  handleClick(arg){
      console.log("HEREw", arg)
      this.props.updateOptions(arg)
      console.log(this.props.Obj)
  }

  render() {
    //console.log("SUPPLIER", this.props)
    // for (lead in this.props.Obj.leads){}
    return (
      <div>
        {this.props.Obj.leads.map(lead => (
        <a href={lead.first_name} onClick={this.showMenu}>
            {lead.first_name} {lead.last_name} 
            <br />
            <br />
        </a>

        ))}
        { 
          this.state.showMenu
            ? (
              <div
                className="menu"
                ref={(element) => {
                  this.dropdownMenu = element;
                }}
              >
                <button value="update" onClick={() => this.handleClick(true)}> Update </button>
                <button value="create" onClick={() => this.handleClick(true)}> Create </button>
              </div>
            )
            : (
              null
            )
        }
      </div>
    );
  }
}

export default Card

The problem here is that the buttons update and delete don't appear under each item.这里的问题是updatedelete按钮不会出现在每个项目下。 They appear at the bottom of both of them.它们出现在两者的底部。 How can would I go about solving this?我该如何解决这个问题?

Put your buttons inside the leads.map loop and make sure to give them each an id.将您的按钮放在leads.map循环中,并确保为每个按钮提供一个 id。 That way they won't all behave as the same button.这样他们就不会像同一个按钮一样工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM