单击时按钮不显示菜单

时间:2021-04-05 22:28:58

标签: reactjs

我正在尝试实现一个显示菜单按钮。问题是当我点击显示菜单时什么也没有发生。任何人都可以帮助解决这个问题吗?我只需要在单击时显示元素。也许我在函数中写错了,因为代码有点长,而且我是 reactjs 的初学者。谢谢。

import React, { Component } from 'react';
import Button from '@material-ui/core/Button';
import FetchRandomBet from "./fetchRandomBets";

const options = [
    { value: 1, label: 'less than 2' },
    { value: 2, label: 'more than 2' },
];

class Betslip extends Component {
    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() {
        return (

            <div className="betslip">

                <div className="betslip-top">
                    <h1 className="text">BETSLIP</h1>
                    <p className="text-two">BET WITH US!</p>

                    <div>
                        <button onClick={this.showMenu}> Show menu</button>
                        {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)}
                    </div>
                </div>

                <div>
                    <FetchRandomBet value={options} />
                </div>

                <Button className="betnow" variant="contained">
                    Bet Now!
                </Button>
            </div>
        );
    }
}

export default Betslip;

0 个答案:

没有答案
相关问题