这就是我现在拥有的:
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>
我想要的是,如果收音机按钮标签在多个线上:
如果无线电按钮标签不采用多行,我需要在同一行上显示广播按钮。I.E。这是OK
当至少一个广播按钮占用一条线时,我希望所有其他按钮也要占据整个线路以符合规定。
因此,我要么每行3个,要么每行1个。我永远不要有一个带有1个单选按钮的行,还有其他带有2或3个广播按钮的行。
我可以建议的一个技巧是通过将标签的框
height
在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;