onClick Dropdown无法在ReactJS中实现

时间:2018-09-07 11:09:58

标签: javascript reactjs

import React, { Component } from "react";
import axios from 'axios';
import "../node_modules/bootstrap/dist/css/bootstrap.min.css";

import Footer from "./components/Footer";
import Banner from "./components/Banner";




class Main extends Component {

  state = {
    topCategory: []
  }

  componentDidMount() {
    axios.get('http://localhost:3030/topCategory')
      .then(res => {
        console.log(res.data.express.catalogGroupView);
        this.setState({
          topCategory: res.data.express.catalogGroupView
        })
      })
  }

  constructor() {
    super();

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

    }
  }


  render() {

    const { topCategory } = this.state;
    const navList = topCategory.map(navList => {

      return (

          <li key={navList.uniqueID} onClick={this.showMenu}>{navList.name}</li>

        )

    })

    return (
      <div>
      <ul className="header">{navList}</ul>
      {
          this.state.showMenu
            ? (
              <div
                className="menu"
                ref={(element) => {
                  this.dropdownMenu = element;
                }}
              >
                <button> Menu item 1 </button>
                <button> Menu item 2 </button>
                <button> Menu item 3 </button>
              </div>
            )
            : (
              null
            )
        }

      <h2>Lorem Ipsum</h2>
      <p>Cras facilisis urna ornare ex volutpat, et
         convallis erat elementum. Ut aliquam, ipsum vitae
         gravida suscipit, metus dui bibendum est, eget rhoncus nibh
         metus nec massa. Maecenas hendrerit laoreet augue
         nec molestie. Cum sociis natoque penatibus et magnis
        dis parturient montes, nascetur ridiculus mus.</p>
      <Banner />
      <Footer />
      </div>

    )

  }


}

export default Main;

我是新来的反应者,尝试在导航上工作。我面临一个特殊的问题。如果我单击导航项,则会出现一个下拉列表。为此,我在li上使用了onClick函数,但是它不起作用。我使用外部API端点填充了顶部导航项。但是,当我单击项目时,应该会出现一个下拉列表。有人可以帮我还是指导我。

导航栏的屏幕截图:

enter image description here

0 个答案:

没有答案