ReactJS:如何为Semantic UI下拉组件设置默认选项?
Hey there! The issue here is that you're using an invalid prop (defaultOption) to set the default selected option for Semantic UI React's Dropdown component. Let me show you how to fix this quickly:
What's Wrong
Semantic UI React's Dropdown doesn't recognize the defaultOption prop. Instead, it uses defaultValue (for uncontrolled components) to set the initial selected option. This value needs to match the value field of the option you want to select, not the key field.
Looking at your lessonGroup array, the "Regular lesson" entry has a value of 'regular'—not 'r' (that's just its key). That's why your initial attempt didn't work.
The Corrected Code
Here's how to update your component to set "Regular lesson" as the default selected option:
// Your existing lessonGroup constant const lessonGroup = [ { key: 'r', value: 'regular', text: 'Regular lesson' }, { key: 'wp', value: 'wp', text: 'Weak Point lesson' }, { key: 'wt', value: 'wt', text: 'World Tour lesson' }, ]; // Updated Dropdown component with correct default selection <Dropdown placeholder='Lesson type' search selection options={lessonGroup} defaultValue='regular' // Matches the "value" of your desired default option />
Bonus: Controlled Component Note
If you later need to control the selected value dynamically (e.g., update it based on user input or state), you'd switch to using the value prop paired with an onChange handler to manage state. For example:
import { useState } from 'react'; function LessonSelector() { const [selectedLesson, setSelectedLesson] = useState('regular'); return ( <Dropdown placeholder='Lesson type' search selection options={lessonGroup} value={selectedLesson} onChange={(e, { value }) => setSelectedLesson(value)} /> ); }
内容的提问来源于stack exchange,提问作者devamat

