如何在Office UI Fabric React下拉组件中标记选中菜单项为已勾选?
Got it! To display a checkmark next to the selected menu item in Office UI Fabric's Dropdown component, you'll need to customize how menu items are rendered and track the selected state with component state. Here's a complete, working implementation based on your code:
Step-by-Step Solution
1. Update Component State & Imports
First, add state to track the selected item's key, and import the checkmark icon from Office UI Fabric:
import * as React from "react"; import { Dropdown, IDropdownItem } from "office-ui-fabric-react/lib/Dropdown"; import { Check } from "office-ui-fabric-react/lib/Icon"; // Import checkmark icon import * as styles from "./dropdownMenu.scss"; export class DropDownMenu extends React.Component<{}, { selectedKey: string | number }> { // Initialize state (set a default key if you want a pre-selected item) public state = { selectedKey: "" };
2. Handle Selection Changes
Add an onChange handler to update the state when the user picks an item:
private handleDropdownChange = ( event: React.FormEvent<HTMLDivElement>, item: IDropdownItem | undefined ) => { if (item) { this.setState({ selectedKey: item.key }); } };
3. Customize Item Rendering
Create a custom onRenderItem function that adds a checkmark to the selected item while preserving default styling:
private renderDropdownItem = ( item: IDropdownItem, defaultRender: (item: IDropdownItem) => JSX.Element ) => { const isSelected = item.key === this.state.selectedKey; return ( <div style={{ display: "flex", alignItems: "center", padding: "8px 16px" }}> {/* Show checkmark only for the selected item */} {isSelected && <Check style={{ marginRight: "8px", color: "#0078d4" }} />} {/* Render the default item text/styling */} {defaultRender(item)} </div> ); };
4. Update the Dropdown Component
Pass the state, handler, and custom renderer to your Dropdown:
public render() { // Example dropdown items (replace with your own) const dropdownItems: IDropdownItem[] = [ { key: "option1", text: "First Option" }, { key: "option2", text: "Second Option" }, { key: "option3", text: "Third Option" } ]; return ( <div className={styles.size}> <Dropdown placeholder="Select an option" items={dropdownItems} selectedKey={this.state.selectedKey} onChange={this.handleDropdownChange} onRenderItem={this.renderDropdownItem} /> </div> ); } }
Key Details
- We use Office UI Fabric's built-in
Checkicon to keep the design consistent with the library's system. - The
defaultRenderparameter lets us reuse the dropdown's default item styling, so we don't have to rebuild it from scratch. - Adjust the padding/icon spacing in the custom div to match your layout needs.
内容的提问来源于stack exchange,提问作者Vardhan Dugar
相关产品推荐
相关产品推荐

