【问题标题】:Place a component inside label of form control label in material ui在材质ui中的表单控件标签的标签内放置一个组件
【发布时间】:2022-01-12 12:27:20
【问题描述】:

我正在使用 Material ui v5,并且在使用 FormControlLabel 时,我想用一些文本和一个按钮来显示我的自定义组件,但我无法在文本和按钮之间添加空格。

我尝试将 justifyContent="space-between" 用于 "@mui/material/Box" 的 Box 组件,但仍然没有变化

这是我得到的,但我希望“项目”和删除按钮之间有空格。

这是我的代码:

import React from "react";
import Checkbox from "@mui/material/Checkbox";
// import FormGroup from "@mui/material/FormGroup";
import FormControlLabel from "@mui/material/FormControlLabel";
import Container from "@mui/material/Container";
import { makeStyles } from "@mui/styles";
import Button from "@mui/material/Button";
import Typography from "@mui/material/Typography";
import Box from "@mui/material/Box";
import IconButton from "@mui/material/IconButton";
import DeleteIcon from "@mui/icons-material/Delete";

const useStyle = makeStyles({
  label: {
    // backgroundColor: "red",
    width: "100%",
    // position: "absolute",
    // right: "10px",
  },
});

export default function TaskItem() {
  const classes = useStyle();
  const Label = (
    <Box
      display="flex"
      justifyContent="space-between"
      alignItems="center"
      className={classes.label}
    >
      <Typography>Item</Typography>
      <IconButton aria-label="delete" size="large">
        <DeleteIcon fontSize="inherit" />
      </IconButton>
    </Box>
  );
  return (
    <>
      <FormControlLabel
        label={Label}
        control={<Checkbox />}
        sx={{ width: "100%" }}
      />
      {/* <Label /> */}
    </>
  );
}

【问题讨论】:

    标签: reactjs material-ui


    【解决方案1】:

    API of Box component 不包括您尝试传递的属性。但是它包含SX prop,你可以通过配置sx属性来达到你想要的效果:

        <Box
          sx={{
            display: 'flex',
            gap: 2
          }}
        >
        ...
    
    

    【讨论】:

    • 我很困惑,因为他们从未在盒子的 API 文档中添加 alignItems 和 justifyContent 道具,但是当我使用时,它们的工作方式与我们传递 sx 道具时完全相同。另外,我想让这个自定义标签占据父级的宽度,有什么解决办法吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-02-10
    • 1970-01-01
    • 1970-01-01
    • 2018-04-10
    • 1970-01-01
    • 2018-08-01
    • 2018-12-09
    相关资源
    最近更新 更多