我正在使用ant设计的下拉菜单,但是无法从下拉列表中激活一个值。如何提供默认值?
<Dropdown
value="1st menu item"
trigger={["click"]}
className={css`
background-color: #0a3150;
height: 65px;
display: flex;
justify-content: space-between;
padding: 0px 28px;
font-size: 17px;
color: white;
align-items: center;
cursor: pointer;
`}
overlay={this.renderList()}
>
<div>
CLick me <Icon type="down" />
</div>
</Dropdown>
它不采用分配的值。
在renderList()
<Menu>
<Menu.Item>1st menu item</Menu.Item>
<Menu.Item>2nd menu item</Menu.Item>
<SubMenu title="sub menu">
<Menu.Item>3rd menu item</Menu.Item>
<Menu.Item>4th menu item</Menu.Item>
</SubMenu>
<SubMenu title="disabled sub menu" disabled>
<Menu.Item>5d menu item</Menu.Item>
<Menu.Item>6th menu item</Menu.Item>
</SubMenu>
</Menu>
//该值在列表中
答案 0 :(得分:2)
如前所述,通常您宁愿使用antD的Select
组件来拥有默认值选项。 (https://ant.design/components/select)
尽管如此,可以使用Dropdown
组件来实现所需的功能。您只需要确保在单击该项目并呈现它(而不是静态值)后保存当前选择的值即可:
import React from "react";
import ReactDOM from "react-dom";
import "antd/dist/antd.css";
import "./index.css";
import { Menu, Dropdown, Icon } from "antd";
const menuItems = [
{
key: 1,
value: "1st menu item"
},
{
key: 2,
value: "2nd menu item"
},
{
key: 3,
value: "3rd menu item"
}
];
const CustomDropdown = () => {
const [selected, setSelected] = React.useState("Select value");
const handleMenuClick = e => {
console.log(e.key);
const newSelected = menuItems.find(item => item.key === parseInt(e.key, 10))
.value;
setSelected(newSelected);
};
const menu = (
<Menu onClick={handleMenuClick}>
{menuItems.map(item => (
<Menu.Item key={item.key}>{item.value}</Menu.Item>
))}
</Menu>
);
return (
<Dropdown overlay={menu} trigger={["click"]}>
<a className="ant-dropdown-link" href="#">
{selected} <Icon type="down" />
</a>
</Dropdown>
);
};
ReactDOM.render(<CustomDropdown />, document.getElementById("container"));
请在此处查看其工作方式: https://codesandbox.io/s/loving-beaver-nxbys