如何在 Material UI (React JS) 中根据需要制作“选择"组件

2022-01-19 00:00:00 reactjs frontend javascript css material-ui

除非有选择的选项,否则我想用红色显示错误.有没有办法做到这一点.

I want to display like an error with red color unless there is a selected option. Is there any way to do it.

推荐答案

要使用 Material UI 设置必填的 Select 字段,您可以这样做:

For setting a required Select field with Material UI, you can do:

class SimpleSelect extends React.PureComponent {
  state = {
    selected: null,
    hasError: false
  }

  handleChange(value) {
    this.setState({ selected: value });
  }

  handleClick() {
    this.setState(state => ({ hasError: !state.selected }));
  }

  render() {
    const { classes } = this.props;
    const { selected, hasError } = this.state;

    return (
      <form className={classes.root} autoComplete="off">
        <FormControl className={classes.formControl} error={hasError}>
          <InputLabel htmlFor="name">
            Name
          </InputLabel>
          <Select
            name="name"
            value={selected}
            onChange={event => this.handleChange(event.target.value)}
            input={<Input id="name" />}
          >
            <MenuItem value="hai">Hai</MenuItem>
            <MenuItem value="olivier">Olivier</MenuItem>
            <MenuItem value="kevin">Kevin</MenuItem>
          </Select>
          {hasError && <FormHelperText>This is required!</FormHelperText>}
        </FormControl>
        <button type="button" onClick={() => this.handleClick()}>
          Submit
        </button>
      </form>
    );
  }
}

CodeSandBox 上的工作演示

相关文章