React评分按钮点击选中异常问题:需点击两次才生效且仅选中首个按钮
Fixing Your React Rating Component's Double-Click & Wrong Selection Issues
Hey there! Let's break down what's tripping up your rating component and fix it up step by step.
What's Going Wrong
First, let's unpack the two main issues in your code:
- Duplicate
idattributes: All your buttons useid='badge'—but HTML requires ids to be unique per page. That's whydocument.getElementById('badge')always targets the first button, no matter which one you click. - Mismanaged state & async state updates: You're using a single boolean state (
Active) to track selection, which can't tell which rating was clicked. Plus, React state updates are asynchronous—so when you callsetActive(true)and immediately checkif(Active), you're still looking at the old (false) value. That's why you need two clicks: the first sets the state, the second triggers the style change (but still on the wrong button).
The Fixed Code
We'll rewrite this to follow React best practices—using state to drive UI instead of direct DOM manipulation, and tracking the selected rating explicitly:
import React, { useState } from 'react' import "../Styles/Rating.css" const ClientRating = (props) => { const { rating } = props; // Track the actual selected rating value (instead of a boolean) const [selectedRating, setSelectedRating] = useState(null); // Handle click: pass the specific rating value to update state const handleRatingClick = (selectedValue) => { setSelectedRating(selectedValue); } return ( <section> {/* Use map to render buttons dynamically (no repeated code!) */} {rating.map((value, index) => ( <button key={index} // Apply active class conditionally based on state className={`badge ${selectedRating === value ? 'active' : ''}`} onClick={() => handleRatingClick(value)} > {value} </button> ))} </section> ) } export default ClientRating
Add This CSS
Update your Rating.css to define the active button styles (no more direct DOM style changes!):
.badge { /* Your existing badge styles here */ } .badge.active { background-color: grey; color: white; }
Key Improvements
- Dynamic rendering: Using
map()to loop through yourratingarray eliminates repetitive button code. - Precise state tracking: Storing the selected rating value (not just a boolean) lets us clearly identify which button is active.
- State-driven UI: Conditional class names replace direct DOM manipulation, which is the React way of handling styles based on state.
- Unique identifiers: The
keyprop ensures React can efficiently update the button list, and we've removed duplicate ids entirely.
内容的提问来源于stack exchange,提问作者pedrocxb
相关产品推荐
相关产品推荐

