首页 > 解决方案 > 如何在 Material UI 中默认选中第一个单选按钮?

问题描述

我的日期范围从今天到 30 天,它们是单选按钮。When selected or is active changes background color, but, I want the first radio button which is today, selected by default. 什么可能是最好的解决方案?

这是供参考的代码

const classes = useStyles();

  const monthNames = [
    "January",
    "February",
    "March",
    "April",
    "May",
    "June",
    "July",
    "August",
    "September",
    "October",
    "November",
    "December"
  ];

  const d = new Date();

  Date.prototype.addDays = function (days) {
    var dat = new Date(this.valueOf());
    dat.setDate(dat.getDate() + days);
    return dat;
  };

  const getDates = (startDate, stopDate) => {
    var dateArray = new Array();
    var currentDate = startDate;
    while (currentDate <= stopDate) {
      dateArray.push(currentDate);
      currentDate = currentDate.addDays(1);
    }
    return dateArray;
  };

  const dateArray2 = getDates(new Date(), new Date().addDays(30));

  useEffect(() => {
    setNewDate(dateArray2);
    setCurrentMonth(monthNames[d.getMonth()]);
  }, []);

  const currday = (dayInDig) => {
    if (dayInDig === 1) {
      return "Mon";
    } else if (dayInDig === 2) {
      return "Tue";
    } else if (dayInDig === 3) {
      return "Wed";
    } else if (dayInDig === 4) {
      return "Thurs";
    } else if (dayInDig === 5) {
      return "Fri";
    } else if (dayInDig === 6) {
      return "Sat";
    } else {
      return "Sun";
    }
  };

  const [radioValue, setRadioValue] = useState("1");

  const handleChange = (e) => {
    const newData = e.target.value;
    var elems = document.querySelectorAll(".toggleButtonNew.active");
    [].forEach.call(elems, function (el) {
      el.classList.remove("active");
    });
    e.target.closest("label").classList.toggle("active");
    setRadioValue(newData);
  };

  const currMonth = (monthInDig) => {
    if (monthInDig === 0) {
      return "1";
    } else if (monthInDig === 1) {
      return "2";
    } else if (monthInDig === 2) {
      return "3";
    } else if (monthInDig === 3) {
      return "4";
    } else if (monthInDig === 4) {
      return "5";
    } else if (monthInDig === 5) {
      return "6";
    } else if (monthInDig === 6) {
      return "7";
    } else if (monthInDig === 7) {
      return "8";
    } else if (monthInDig === 8) {
      return "9";
    } else if (monthInDig === 9) {
      return "10";
    } else if (monthInDig === 10) {
      return "11";
    }
  };

  console.log("RADIO", radioValue);

  return (
    <>
      <h3>{currentMonth}</h3>
      <GridList className={classes.gridList} cols={3}>
        {Object.keys(newDate).map((key, i) => (
          <ButtonGroup toggle style={{ width: "100%", borderRadius: "20px" }}>
            <GridListTile style={gridListStyleDates}>
              <h5>{currday(newDate[key].getDay())}</h5>
              <ToggleButton
                className="toggleButtonNew"
                key={i}
                type="radio"
                active="true"
                variant="light"
                name="radio"
                value={
                  newDate[key].getFullYear() +
                  "-" +
                  currMonth(newDate[key].getMonth()) +
                  "-" +
                  newDate[key].getDate()
                }
         
        checked={dateValue === newDate[key].getDate()} {/* It selects the radio button */}
        {/* checked={newDate[Object.keys(newDate)[0]].getDate()} */} {/* This code selects all dates */} 

         {/* My intention is to set selected the first radio button i.e today's date */}


                onChange={(e) => {
                  handleChange(e);
                }}
              >
                {newDate[key].getDate()}
              </ToggleButton>
            </GridListTile>
          </ButtonGroup>
        ))}
        
      </GridList>
    </>
  );
}

这是代码和框链接:https ://codesandbox.io/s/material-demo-forked-hcbxl

标签: javascriptreactjsmaterial-ui

解决方案


您需要更改初始状态:

const [radioValue, setRadioValue] = useState("1");

你能猜出你需要把它改成什么吗?

我想要今天的第一个单选按钮,默认选中


推荐阅读