radio按钮放置取决于其标签长度

问题描述 投票:0回答:1

这就是我现在拥有的:

enter image description here

html代码就是这样(我正在使用react的材料-UI):

      <FormControl>
        <FormGroup row>
          <Grid container>
            {options?.map((el, i) => (
              <Grid item xs={12} sm={6} md={4} key={i}>
                <FormControlLabel
                  control={<Checkbox size="small" />}
                  label={<Typography>{el.description}</Typography>}
                />
              </Grid>
            ))}
          </Grid>
        </FormGroup>
      </FormControl>

我想要的是,如果收音机按钮标签在多个线上

enter image description here

如果无线电按钮标签不采用多行,我需要在同一行上显示广播按钮。

I.E。这是OK

enter image description here 当至少一个广播按钮占用一条线时,我希望所有其他按钮也要占据整个线路以符合规定。 因此,我要么每行3个,要么每行1个。我永远不要有一个带有1个单选按钮的行,还有其他带有2或3个广播按钮的行。

实现这一目标的最佳方法是什么(甚至更改HTML)?

我可以建议的一个技巧是通过将标签的框

height

用内容
javascript html css material-ui
1个回答
0
投票
划分来计算内容的行数。如果行数大于1,则应在一列中显示(在您的情况下为3行),否则应在乘列中显示(在您的情况下为1行)。

在ADDICANTION上,我在

useEffect
依赖项中添加了选项对象,如果内容动态更改,则应重新计算其位置。您可以根据您的情况进行修改。 below是在我本地上使用的代码。
import { useState, useEffect, useRef } from "react";
import {
  FormControl,
  FormGroup,
  FormControlLabel,
  Checkbox,
  Typography,
  Grid2
} from "@mui/material";

const CheckboxGroup = ({ options }) => {
  const [singleColumn, setSingleColumn] = useState(false);
  const labelRefs = useRef([]);

  useEffect(() => {
    let maxLabelHeight = 0;

    labelRefs.current.forEach(labelEl => {
      if (!labelEl) return;
      const style = window.getComputedStyle(labelEl);
      const elementLineHeight = Number(style.lineHeight.split("px")[0]);
      const labelHeight = labelEl.clientHeight / elementLineHeight;
      if (labelHeight > maxLabelHeight) {
        maxLabelHeight = labelHeight;
      }
    });

    setSingleColumn(maxLabelHeight > 1);
  }, [options]);

  return (
    <FormControl>
      <FormGroup>
        <Grid2
          container
          spacing={2}
          flexDirection={singleColumn ? "column" : "row"}
          flexWrap="nowrap"
        >
          {options?.map((el, i) => (
            <Grid2 item key={i}>
              <FormControlLabel
                style={{ border: "1px solid black" }}
                control={<Checkbox size="small" />}
                label={
                  <Typography ref={el => (labelRefs.current[i] = el)}>
                    {el.description}
                  </Typography>
                }
              />
            </Grid2>
          ))}
        </Grid2>
      </FormGroup>
    </FormControl>
  );
};

export default CheckboxGroup;

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.