React-Bootstrap中onSelect应绑定在MenuItem还是DropdownButton?
Hey there! Let's tackle your questions about React-Bootstrap's DropdownButton and MenuItem components:
1. Where to bind the onSelect event?
You can bind onSelect either on individual MenuItems or on the parent DropdownButton—it depends on how you want to handle selection logic:
- Bind on
MenuItemif you need unique handling for each menu option (e.g., different actions for Item 1 vs Item 2). - Bind on
DropdownButtonif you want a single handler for all menu selections (great for simple "select and update state" use cases like yours).
2. Fixing the selected state sync issue
The reason your DropdownButton isn't updating its title after selection is because you're using a hardcoded string ("--Select One--") instead of linking it to a reactive state variable. Here's a complete working example using React's useState hook:
import { useState } from 'react'; import { DropdownButton, MenuItem } from 'react-bootstrap'; function DocumentTypeSelector() { // State to track the selected option const [selectedItem, setSelectedItem] = useState("--Select One--"); // Handler for menu selection (can be used on DropdownButton or MenuItem) const handleSelect = (eventKey) => { setSelectedItem(eventKey); }; return ( <div className="select_option"> <label htmlFor="document-type">Document Desc</label> <DropdownButton title={selectedItem} id="document-type" onSelect={handleSelect} // Single handler for all menu items > {/* Pass the item text as eventKey, mark active if it's the selected one */} <MenuItem eventKey="Item 1" active={selectedItem === "Item 1"}> Item 1 </MenuItem> <MenuItem eventKey="Item 2" active={selectedItem === "Item 2"}> Item 2 </MenuItem> <MenuItem eventKey="Item 3" active={selectedItem === "Item 3"}> Item 3 </MenuItem> </DropdownButton> </div> ); } export default DocumentTypeSelector;
Key points in this example:
- We use
useStateto store the currently selected item, which keeps the UI reactive. - The
DropdownButton'stitleis set toselectedItem, so it updates automatically when the state changes. - The
onSelecthandler is attached to theDropdownButton—it receives theeventKeyof the clickedMenuItemand updates the state. - Each
MenuItemhas anactiveprop that highlights the currently selected option, improving UX.
If you prefer to handle selection per MenuItem, you can pass a unique handler to each one instead:
<MenuItem eventKey="Item 1" active={selectedItem === "Item 1"} onSelect={() => setSelectedItem("Item 1")} > Item 1 </MenuItem>
Either approach will fix the sync issue—pick the one that fits your use case best!
内容的提问来源于stack exchange,提问作者amitpowerpeace

