React material-UI覆盖默认表单输入样式

时间:2018-03-20 14:38:59

标签: reactjs material-ui

我想覆盖默认的表单输入样式,所以我在下面的代码~f modifier。问题是我想添加表单输入的import React from 'react'; import { withStyles } from 'material-ui/styles'; import TextField from 'material-ui/TextField'; const styles = theme => ({ textFieldRoot: { padding: 0, 'label + &': { marginTop: theme.spacing.unit * 3, }, }, textFieldInput: { borderRadius: 4, backgroundColor: theme.palette.common.white, border: '1px solid #ced4da', fontSize: 16, padding: '10px 12px', width: 'calc(100% - 24px)', transition: theme.transitions.create(['border-color', 'box-shadow']), '&:focus': { borderColor: '#80bdff', boxShadow: '0 0 0 0.2rem rgba(0,123,255,.25)', }, }, textFieldFormLabel: { fontSize: 18, }, }); function CustomizedInputs(props) { const { classes } = props; return ( <div className={classes.container}> <TextField defaultValue="react-bootstrap" label="Bootstrap" id="bootstrap-input" InputProps={{ disableUnderline: true, classes: { root: classes.textFieldRoot, input: classes.textFieldInput, }, }} InputLabelProps={{ shrink: true, className: classes.textFieldFormLabel, }} /> </div> ); } export default withStyles(styles)(CustomizedInputs); ,但我不知道如何。任何人都可以帮助我在错误状态下为输入添加红色边框吗?非常感谢你!

--headless

1 个答案:

答案 0 :(得分:0)

您可以使用regex以某种方式处理此问题,Redux也有validate属性,但此示例使用onChange运行检查函数,如果存在则设置布尔值一个错误。然后该布尔值确定输入将选择哪个类名。

import React from 'react';
import { withStyles } from 'material-ui/styles';
import TextField from 'material-ui/TextField';

const styles = theme => ({
  textFieldRoot: {
    padding: 0,
    'label + &': {
      marginTop: theme.spacing.unit * 3,
    },
  },
  textFieldError: {
    border: '1px solid red',
  },
  textFieldInput: {
    borderRadius: 4,
    backgroundColor: theme.palette.common.white,
    border: '1px solid #ced4da',
    fontSize: 16,
    padding: '10px 12px',
    width: 'calc(100% - 24px)',
    transition: theme.transitions.create(['border-color', 'box-shadow']),
    '&:focus': {
      borderColor: '#80bdff',
      boxShadow: '0 0 0 0.2rem rgba(0,123,255,.25)',
    },
  },
  textFieldFormLabel: {
    fontSize: 18,
  },
});

function CustomizedInputs(props) {
  const { classes } = props;

  const checkField = () => {
    // some condition to check for error
    errorVariable = true
  }

  return (
    <div className={classes.container}>
      <TextField
        defaultValue="react-bootstrap"
        label="Bootstrap"
        id="bootstrap-input"
        onChange={checkField}
        InputProps={{
          disableUnderline: true,
          classes: {
            root: classes.textFieldRoot,
            input: errorVariable ? classes.textFieldError : classes.textFieldInput,
          },
        }}
        InputLabelProps={{
          shrink: true,
          className: classes.textFieldFormLabel,
        }}
      />
    </div>
  );
}

export default withStyles(styles)(CustomizedInputs);