如何使用 React Material-UI 创建 2 列表单?

IT技术 reactjs material-ui
2021-05-10 19:41:05

我正在创建一个带有 material-ui 的react形式。

我希望表单是一个固定的 2 列视图,而不是基于浏览器大小的流动,所以它总是这样的:

|First Name      |Last Name|
|Street Address  |City     |

而不是最终像

|First Name      |Last Name|  Street Address  |City     |

https://codesandbox.io/s/0q7kw76nyl

import React from "react";
import PropTypes from "prop-types";
import { withStyles } from "@material-ui/core/styles";
import TextField from "@material-ui/core/TextField";

const styles = theme => ({
  textField: {
    marginLeft: theme.spacing.unit,
    marginRight: theme.spacing.unit
  }
});

class TextFields extends React.Component {
  state = {
    firstName: "",
    lastName: "",
    street: "",
    city: ""
  };

  handleChange = name => event => {
    this.setState({ [name]: event.target.value });
  };

  render() {
    const { classes } = this.props;

    return (
      <form className={classes.container} noValidate autoComplete="off">
        <TextField
          id="first-name"
          label="First Name"
          className={classes.textField}
          value={this.state.firstName}
          onChange={this.handleChange("firstName")}
          margin="normal"
        />

        <TextField
          id="last-name"
          label="Last Name"
          className={classes.textField}
          value={this.state.lastName}
          onChange={this.handleChange("lastName")}
          margin="normal"
        />

        <TextField
          id="address-street"
          label="Street Address"
          className={classes.textField}
          value={this.state.street}
          onChange={this.handleChange("street")}
          margin="normal"
        />

        <TextField
          id="address-city"
          label="City"
          className={classes.textField}
          value={this.state.city}
          onChange={this.handleChange("city")}
          margin="normal"
        />
      </form>
    );
  }
}

TextFields.propTypes = {
  classes: PropTypes.object.isRequired
};

export default withStyles(styles)(TextFields);
3个回答

如上所述,放入 div 效果很好。

您还可以将它们放在网格布局中以进行额外的自定义。

网格布局有一些简洁的附加功能,例如项目的间距和对齐方式、可自定义的项目宽度,这里是文档

import Grid from '@material-ui/core/Grid'
<Grid container>
     <Grid item xs={6}> 
         ... 
     </Grid>
     <Grid item xs={6}>
         ...
     </Grid>
</Grid>

尝试将这两个组分成 div,如下所示:

https://codesandbox.io/s/vy6k6w1jq3

<div>
 <TextField/>
 <TextField/>
</div>
<div>
 <TextField/>
 <TextField/>
</div>

您可以同时使用 Grid 容器和项目。

<Grid container spacing={2} >
  <Grid container item xs={6} direction="column" >
    <TextField />
    <TextField />
    <TextField />
  </Grid>
  <Grid container item xs={6} direction="column" >
    <TextField />
    <TextField />
  </Grid>
</Grid>