You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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:

  1. Duplicate id attributes: All your buttons use id='badge'—but HTML requires ids to be unique per page. That's why document.getElementById('badge') always targets the first button, no matter which one you click.
  2. 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 call setActive(true) and immediately check if(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 your rating array 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 key prop ensures React can efficiently update the button list, and we've removed duplicate ids entirely.

内容的提问来源于stack exchange,提问作者pedrocxb

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 23:17:35