ReactJS material-ui 使用类 `Mui-disabled` 作为只读组件

win*_*ter 3 reactjs material-ui

我正在构建一个新组件TextField,我需要为具有readOnlythandisabled属性的文本字段应用相同的样式。

所以,我试图使用该属性,className但它不起作用。

// some logic here ..

<TextField
    {...props}
    className={readOnly ? 'Mui-disabled' : undefined}
 />
Run Code Online (Sandbox Code Playgroud)

所以,我也尝试使用classsesprop,但我不知道如何从禁用的类中获取当前配置。

Rya*_*ell 5

当您使用该disabled属性时,Material-UI 会将Mui-disabled类放置在许多不同的元素上。要获得相同的外观,您需要将其添加到所有相同的元素中。

下面是如何执行此操作的示例。除了添加Mui-disabled类之外,还需要覆盖下划线的“聚焦”样式(通过:after伪类处理)。

import React from "react";
import ReactDOM from "react-dom";

import TextField from "@material-ui/core/TextField";
import { makeStyles } from "@material-ui/core/styles";
const disabledClassNameProps = { className: "Mui-disabled" };
const useStyles = makeStyles(theme => {
  const light = theme.palette.type === "light";
  const bottomLineColor = light
    ? "rgba(0, 0, 0, 0.42)"
    : "rgba(255, 255, 255, 0.7)";
  return {
    underline: {
      "&.Mui-disabled:after": {
        borderBottom: `1px dotted ${bottomLineColor}`,
        transform: "scaleX(0)"
      }
    }
  };
});
function App() {
  const classes = useStyles();
  return (
    <div className="App">
      <TextField
        {...disabledClassNameProps}
        inputProps={{ readOnly: true }}
        InputProps={{ ...disabledClassNameProps, classes }}
        InputLabelProps={disabledClassNameProps}
        FormHelperTextProps={disabledClassNameProps}
        label="Test Disabled Look"
        defaultValue="Some Text"
        helperText="Helper Text"
      />
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
Run Code Online (Sandbox Code Playgroud)

编辑 TextField 只读看起来已禁用

相关回答: