状态未在按钮上更新单击

时间:2020-10-19 16:40:14

标签: reactjs state use-state

我是新来的反应者。我的组件中有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;

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

预先感谢

0 个答案:

没有答案