创建一个带有文本字段的 Material Ui 复选框

Create a Material Ui checkbox with textfiled

如何创建一个 Material ui 复选框,选中后将禁用文本字段并修复对齐方式?

Link 到沙箱:

https://codesandbox.io/s/material-demo-forked-mfnqk?file=/demo.tsx

你应该使用 List component provided by Material UI. Give it the alignItems="center" prop to fix the alignment. Then, the Material UI Checkboxes component accepts a boolean for the disabled prop so you should have that set to the value of 'checked' in your state hooks. That way, when 'checked' is updated, the disabled prop updates as well. I also added a fullWidth prop to the textField to make it less cluttered. A live demo can be found here,但我是这样计算的:

import React from "react";
import Checkbox from "@material-ui/core/Checkbox";
import TextField from "@material-ui/core/TextField";
import List from "@material-ui/core/List";
import ListItem from "@material-ui/core/ListItem";
import Typography from "@material-ui/core/Typography";

export default function Checkboxes() {
  const [checked, setChecked] = React.useState(false);

  const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    setChecked(event.target.checked);
  };

  return (
    <>
      <List>
        <ListItem alignItems="center">
          <Checkbox
            checked={checked}
            onChange={handleChange}
            inputProps={{ "aria-label": "primary checkbox" }}
          />
          <TextField
            fullWidth
            disabled={checked}
            label="disable when checkbox checked"
          />
        </ListItem>
        <ListItem alignItems="center">
          <Typography variant="subtitle1" style={{ marginRight: "3px" }}>
            Hello
          </Typography>
          <TextField
            fullWidth
            disabled={!checked}
            label="enable when checkbox checked"
          />
        </ListItem>
      </List>
    </>
  );
}
<Grid container alignContent="center" alignItems="center" direction="row" xs={12}>
    <Grid item xs="auto">
        <Checkbox />
    </Grid>
    <Grid item xs>
        <TextField fullWidth label="I am a Textbox" />
    </Grid>
</Grid>

这应该有效。