简体   繁体   中英

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:

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. 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. That way they won't all behave as the same button.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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