javascript - 如何根据所选选项显示两个链接?
问题描述
我有两个键/值。根据选择,我想显示简单的链接。If I select first option it will display two links and when the second option is selected it will display another two links. 如何显示它们?
这是我当前的代码
import React from "react"
import { Dropdown, Menu, Icon } from 'antd'
class DropOption extends React.Component {
state = {
visible: false,
};
handleMenuClick = (e) => {
if (e.key === '1') {
}
else {
}
}
render() {
const menu = (
<Menu onClick={this.handleMenuClick}>
<Menu.Item key="1">CULT-4A</Menu.Item>
<Menu.Item key="2">HIN-4A</Menu.Item>
</Menu>
)
return (
<div align="center">
<Dropdown
overlay={menu}>
<a className="ant-dropdown-link" href="#">
Select one option<Icon type="down" />
</a>
</Dropdown>
</div>
)
}
}
export default DropOption
解决方案
您应该使用组件的状态。setState({ key: value })
您可以使用该方法更改组件的状态值。
handleMenuClick = e => {
this.setState({ selectedOption: e.key });
};
然后可以通过使用在Render
方法中使用状态值this.state.key
<div>
{this.state.selectedOption === "option1" && (
<ul>
<li>
<a href="/link1">Option 1 - link1</a>
</li>
<li>
<a href="/link1">Option 1 - link2</a>
</li>
</ul>
)}
</div>
您还可以从数组构建菜单:
import React from "react";
import ReactDOM from "react-dom";
import "antd/dist/antd.css";
import { Dropdown, Menu, Icon } from "antd";
class DropOption extends React.Component {
state = { selectedOption : null };
handleMenuClick = e => {
this.setState({ selectedOption: e.key });
};
items = [
{
key: "option1",
text: "CULT-4A",
links: [
{ text: "option1 - link1", url: "/linkCULT-1" },
{ text: "option1 - link2", url: "/linkCULT-2" }
]
},
{
key: "option2",
text: "HIN-4A",
links: [
{ text: "option2 - link1", url: "/linkHIN-1" },
{ text: "option2 - link2", url: "/linkHIN-2" }
]
}
];
render() {
const currentItem = this.items.find(
item => item.key === this.state.selectedOption
);
const links = currentItem ? currentItem.links : [];
console.log(links);
const menu = (
<Menu onClick={this.handleMenuClick}>
{this.items.map(item => (
<Menu.Item key={item.key}>{item.text}</Menu.Item>
))}
</Menu>
);
return (
<div align="center">
<Dropdown overlay={menu}>
<a className="ant-dropdown-link" href="#">
Select one option
<Icon type="down" />
</a>
</Dropdown>
{links.length > 0 && (
<div>
<ul>
{links.map(link => {
return (
<li key="{link.url}">
<a href="{link.url}">{link.text}</a>
</li>
);
})}
</ul>
</div>
)}
</div>
);
}
}
export default DropOption;
const rootElement = document.getElementById("root");
ReactDOM.render(<DropOption />, rootElement);
有关工作示例,请参阅https://codesandbox.io/s/qxjknok10j
推荐阅读
- excel-formula - Power BI 查找重复项,然后查找它们是否在其他列中完全相同
- android - Android 和 AdMob 广告未展示
- authentication - 从 Lambda (NodeJS) 到 RDS 的 IAM 身份验证
- office-js - Office JS - 在附加之前编辑 txt 文件
- django - Django - 如何获取提交到表单的文件?
- gem5 - 在 gem5 中建模端口争用
- firebase - 如何从云 Firestore 中的存储中引用图像?反应
- constants - 如何在 Tcl 中创建常量?
- java - 如何在 Recycler 视图上使用 onFling 手势检测器监听器
- python - 如何通过按“r”按钮重新启动我的程序?