无法将文本对齐方式应用于Material UI Input Component,但其他所有方法都可以

时间:2019-07-10 22:08:52

标签: reactjs material-ui

当我检查时,似乎我实际上创建的所有输入样式都转到外部div材质UI创建的包装了Input的输入。但是其他样式也可以用,所以我不确定发生了什么事

const useStyles = makeStyles(theme => ({
  formControl: {
    ...
  },
  label: {
    ...
  },
  input: {
    color: "black",
    '&:after': {
      borderColor: 'black',
      textAlign: 'center'
    },
    fontSize: getFontSize(),
    display: 'flex',
    alignItems: 'center'  // this is the only thing that does NOT work
  }
}));

const classes = useStyles();

<FormControl className={classes.formControl}>
  {
    labelText &&
    <InputLabel
      className={classes.label}
      htmlFor="component-helper"
    >
      {labelText}
    </InputLabel>
  }
  <Input
    className={classes.input}
    classes={{textAlign: 'center'}}  // this does NOT work either
    id={"component-helper"}
    value={text}
    onBlur={handleBlur}
    onChange={handleChange}
    aria-describedby="component-helper-text"
  />
</FormControl>

2 个答案:

答案 0 :(得分:2)

问题中包含以下代码的主要问题:

  <Input
    className={classes.input}
    classes={classes.inputElement}  // this does NOT work either
    id={"component-helper"}
    value={text}
    onBlur={handleBlur}
    onChange={handleChange}
    aria-describedby="component-helper-text"
  />

classes属性应如下所示:

  <Input
    className={classes.input}
    classes={{input: classes.inputElement}}
    id={"component-helper"}
    value={text}
    onBlur={handleBlur}
    onChange={handleChange}
    aria-describedby="component-helper-text"
  />

下面是一个有效的示例。我用过

classes={inputClasses}

在我的示例中,但这等同于

classes={{root: inputClasses.root, input: inputClasses.input}}
import React from "react";
import ReactDOM from "react-dom";
import { makeStyles, FormControl, InputLabel, Input } from "@material-ui/core";

const useInputStyles = makeStyles(theme => ({
  root: {
    color: "black",
    "&:after": {
      borderColor: "black"
    },
    fontSize: 12
  },
  input: {
    textAlign: "center"
  }
}));

function App() {
  const inputClasses = useInputStyles();
  const labelText = "Test Label";
  return (
    <FormControl>
      <InputLabel htmlFor="component-helper">{labelText}</InputLabel>
      <Input
        classes={inputClasses}
        id="component-helper"
        aria-describedby="component-helper-text"
      />
    </FormControl>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

Edit Input classes

答案 1 :(得分:0)

对于material-ui元素,“ className”用于包装器元素。如文件中所述。因此,这是正确的行为。该文件还说,“类”道具是要覆盖或扩展应用于组件的样式。执行以下操作-

classes={{input: classes.input}}