React Js onClick下拉菜单打开



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

这是我的代码

您可以为每个按钮使用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;

您对渲染的每个按钮都使用相同的打开状态。

通过分析代码,我可以想到的一个可能的解决方案是,您可以创建一个openButtonKeyState,并用每个按钮的唯一标识符映射这些标识符,在这种情况下,可以是objectName。然后在onClick处理程序上,向该数组添加或删除键。

最新更新