首页 > 解决方案 > React Js onClick 下拉菜单打开

问题描述

当我按下一个按钮时,两个按钮都打开。我只想打开我按下的按钮。我该怎么做?

这是我的代码

标签: javascriptreactjs

解决方案


您可以为每个按钮使用 id。这里的例子:

import React, { Component, Fragment } from "react";
import Data from "./parameters.json";
import { Table } from "react-bootstrap";

class Parameter extends Component {
  container = React.createRef();
  state = {
    open: null,
    handleOpen: false,
    selectedOptions: []
  };

  handleButtonClick = (e) => {
    const id = parseInt(e.target?.id);

    if (this.state.open && this.state.open !== id)
      return;

    this.setState((state) => {
      return {
        open: state.open !== 0 && !state.open ? id : null
      };
    });
  };
  handleChange = (selectedOptions) => {
    this.setState({ selectedOptions });
  };

  render() {
    const uniqueTags = [];
    Data.map((img) => {
      if (uniqueTags.indexOf(img.groupName) === -1) {
        uniqueTags.push(img.groupName);
      }
    });

    return (
      <div>
        <Table style={{ width: "100%" }}>
          <thead>
            <tr>
              <th>Parameter Name</th>
            </tr>
          </thead>
          <tbody>
            {uniqueTags.map((value, index) => {
              return (
                <Fragment>
                  <tr>
                    <button
                      type="button"
                      className="button"
                      onClick={this.handleButtonClick}
                      id={index}
                    >
                      <div id={index} style={{ marginLeft: "30px" }}>
                        <td id={index}>▼{value}</td>
                      </div>
                    </button>
                  </tr>
                  {this.state.open === index &&
                    Data.map(
                      (item) =>
                        item.zeroBasedEnumeration !== "0" &&
                        item.groupName === value && (
                          <tr>
                            <td style={{ paddingLeft: "80px" }}>
                              {item.objectName}
                            </td>
                          </tr>
                        )
                    )}
                </Fragment>
              );
            })}
          </tbody>
        </Table>
      </div>
    );
  }
}

export default Parameter;

推荐阅读