首页 > 解决方案 > 状态未更新按钮单击

问题描述

我是新来的反应。我的组件中有 3 个按钮,并且我正在根据选择应用一个活动的类。(即单击的按钮)。

代码是,

import React, { useState, useEffect } from 'react';
import PropTypes from 'prop-types';
import styles from './style.module.scss';

const rootClass = 'headers';

function Headers(props) {
  const {
    content, onClick, displayMonth,
  } = props;

  const [activeMonth, setActiveMonth] = useState(true);
  const [activeWeek, setActiveWeek] = useState(false);
  const [activeYear, setActiveYear] = useState(false);

  const handleClick = (value) => {
    switch (value) {
      case 'week':
        setActiveMonth(false);
        setActiveWeek(true);
        setActiveYear(false);
        console.log('Week:', activeWeek);
        console.log('Month:', activeMonth);
        console.log('Year:', activeYear);
        onClick(value);

        break;
      case 'month':
        setActiveMonth(true);
        setActiveWeek(false);
        setActiveYear(false);
        console.log('Week:', activeWeek);
        console.log('Month:', activeMonth);
        console.log('Year:', activeYear);
        onClick(value);
        break;
      case 'year':
        setActiveYear(true);
        setActiveWeek(false);
        setActiveMonth(false);
        onClick(value);

        break;
      default:
        break;
    }
  };
  return (
    <section className={rootClass}>
      <div className={styles[`${rootClass}__outer-container`]}>
       <div className={`${styles[`${rootClass}__column-container-side`]} ${styles[`${rootClass}__calendar-type`]}`}>
          <button
            type="button"
            className={activeYear ? `${styles[`${rootClass}__event-button`]} ${styles[`${rootClass}__event-year`]} ${styles[`${rootClass}__event-active`]}` : `${styles[`${rootClass}__event-button`]} ${styles[`${rootClass}__event-year`]}`}
            onClick={() => handleClick('year')}
          >
            Year
          </button>
          <button
            type="button"
            className={activeMonth ? `${styles[`${rootClass}__event-button`]} ${styles[`${rootClass}__event-month`]} ${styles[`${rootClass}__event-active`]}` : `${styles[`${rootClass}__event-button`]} ${styles[`${rootClass}__event-month`]}`}
            onClick={() => handleClick('month')}
          >
            Month
          </button>
          <button
            type="button"
            className={activeWeek ? `${styles[`${rootClass}__event-button`]} ${styles[`${rootClass}__event-week`]} ${styles[`${rootClass}__event-active`]}` : `${styles[`${rootClass}__event-button`]} ${styles[`${rootClass}__event-week`]}`}
            onClick={() => handleClick('week')}
          >
            Week
          </button>
        </div>
      </div>
    </section>
  );
}
export default Headers;

当按钮被切换时,状态似乎没有更新。当我控制台日志时,按钮状态保持不变。活动的课程没有得到应用。我究竟做错了什么?请帮忙。

提前致谢

标签: reactjsstateuse-state

解决方案


推荐阅读