如何根据材质UI(React JS)中的需要制作“选择”组件 [英] How to make a 'Select' component as required in Material UI (React JS)

查看:53
本文介绍了如何根据材质UI(React JS)中的需要制作“选择”组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

除非有选定的选项,否则我希望显示为红色错误。
有没有办法做到这一点。

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.Component {
  state = {
    selected: null,
    hasError: false
  };

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

  handleClick() {
    this.setState({ hasError: false });
    if (!this.state.selected) {
      this.setState({ hasError: true });
    }
  }

  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上的工作演示



Working Demo on CodeSandBox

这篇关于如何根据材质UI(React JS)中的需要制作“选择”组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆