【问题标题】:How to make first radio button selected by default in Material UI?如何在 Material UI 中默认选中第一个单选按钮?
【发布时间】:2021-07-01 17:23:44
【问题描述】:

我有从今天到 30 天的日期,这些日期是单选按钮。选中或活动更改背景颜色时,但是,我希望默认选择的第一个单选按钮。什么是最好的解决方案?

这里是参考代码

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>
    </>
  );
}

这里是codeandbox链接:https://codesandbox.io/s/material-demo-forked-hcbxl

【问题讨论】:

    标签: javascript reactjs material-ui


    【解决方案1】:

    你需要改变你的初始状态:

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

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

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

    【讨论】:

    • 我们可以改变什么?
    【解决方案2】:

    您只需要执行以下操作:

    const [radioValue, setRadioValue] = useState(new Date().getDate());
    
    

    它将默认选择Today。我已经更新了你的沙箱代码here

    我可以在第 28 行看到,你已经有了

    const d = new Date();
    

    为了您的代码的一致性并避免将来出现任何代码异味,您可以重复使用它并执行以下操作:

    const [radioValue, setRadioValue] = useState(d.getDate());
    
    

    【讨论】:

      【解决方案3】:

      似乎您的radioValue 是字符串类型,而您将其与整数匹配。最快的解决方案是更改 useState 中的类型:

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

      到这里:

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

      【讨论】:

      • 我做了更改,但没有效果
      猜你喜欢
      • 2017-04-05
      • 2021-11-12
      • 1970-01-01
      • 2013-01-28
      • 1970-01-01
      • 1970-01-01
      • 2018-12-26
      • 1970-01-01
      相关资源
      最近更新 更多