首页 > 解决方案 > 在 ReactJS 中,如何使用 map() 为每个项目创建下拉菜单?

问题描述

我已经尝试了几个小时来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

这里的问题是按钮updatedelete没有出现在每个项目下。它们出现在两者的底部。我该如何解决这个问题?

标签: javascriptnode.jsreactjs

解决方案


将您的按钮放入leads.map循环中,并确保为每个按钮提供一个 id。这样他们就不会都表现得像同一个按钮。


推荐阅读