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

React Hooks实现情绪组件首次渲染无选中状态的方案咨询

解决方案

你当前的代码混合了原生DOM操作和React逻辑,不符合React数据驱动的设计思想,修改后用useState就能轻松实现默认无选中的效果,核心是将选中的评分值存在state中,初始值设为null。

修改后的完整代码:

import React, { useState } from "react";
import {Row, Col} from "react-bootstrap";

import Button from "../../elements/buttons/Button";
import Icon from "../../elements/icons/Icon";
import "./FacialReactions.scss";

// 表情配置抽成数组,方便后续维护
const moodList = [
  { rate: 1, icon: "mood-vbad", text: "很差" },
  { rate: 2, icon: "mood-bad", text: "较差" },
  { rate: 3, icon: "mood-neutral", text: "一般" },
  { rate: 4, icon: "mood-good", text: "不错" },
  { rate: 5, icon: "mood-vgood", text: "很好" },
]

export default function Emoji() {
  // 初始值设为null,代表未选中任何表情
  const [selectedRate, setSelectedRate] = useState(null);

  return (
    <>
      <div className="feedback">
        <div className="containerText">
          <div className="text" style={{justifyContent: 'center'}}>
            <span className="first" > How you were feeling </span>&nbsp;
            <span className="second" style={{color: '#FFA196'}}> before you </span>&nbsp;
          </div>
          <span className="third" style={{color: '#FFA196',justifyContent:'center'}}>you used the vibrator ?</span>
        </div>

        <div className="feedback_ratings">
          {moodList.map(item => (
            <span
              key={item.rate}
              // 动态判断是否加激活类
              className={`feedback_rating ${selectedRate === item.rate ? 'rating_active' : ''}`}
              onClick={() => setSelectedRate(item.rate)}
              data-rate={item.rate}
            >
              <Icon icon={item.icon} variant="horizontal" />
            </span>
          ))}
        </div>
        <div className="feedback-n">
          {/* 选中了才显示提示 */}
          {selectedRate && (
            <section className="feedback_notice">
              <p>
                {selectedRate < 3
                  ? `Sorry to heard that ${moodList.find(item => item.rate === selectedRate).text}! Thank you for the feedback `
                  : `${moodList.find(item => item.rate === selectedRate).text}! Thank you`
                }
              </p>
            </section>
          )}
        </div>
      </div>
    </>
  );
};

修改说明:

  • 移除了所有原生DOM操作、事件监听的逻辑,全部改用React的状态驱动实现,避免内存泄漏问题
  • 初始状态下selectedRate为null,没有表情会匹配激活类的判断条件,自然就没有默认选中的表情
  • 点击表情时更新selectedRate的值,自动触发组件重新渲染,动态更新激活状态和底部提示

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 15:00:00