更改 MUI 文本字段的多个组件根

2024-03-20

根据此处的 MUI Textfield API,Textfield 是以下组件之上的简单抽象

  1. 表单控件
  2. Input
  3. 输入标签
  4. 填充输入
  5. 概述输入
  6. Input
  7. 表单辅助文本

因此,要更改上述任何组件的 Textfield 样式,例如 notchedOutline 类,它是 OutlinedInput 的类,我可以执行以下操作

import { TextField } from '@material-ui/core';

const style = theme => ({
  notchOutline: { /*style in here*/ }
});

<TextField
    inputProps={{ notchedOutline : classes.notchedOutline }}
>
</TextField>

如果子组件类仅对于该组件是唯一的,那么所有这一切都可以实现。

我的问题是,我如何为更常见的命名类设计样式,比如我想同时修改 OutlinedInput、InputLabel、FormHelperText 的根类或 TextField 内的更多子组件?我认为这行不通?

<TextField
    FormControlProps={{ root: classes.root }}
    OutlinedInputProps={{ root: classes.root, notchedOutline : classes.notchedOutline }}
>
</TextField>

or

<TextField
    inputProps={{ 
        root: classes.OutlinedInputRoot, 
        root : classes.FormHelperTextRoot 
    }}
>
</TextField>

需要帮助了解如何瞄准 TextField 子组件的特定根,而不需要触及全局 MUI 主题,或者根本不使用提供的 TextField,而是使用其上的这些子组件构建文本字段组件。


下面的示例展示了如何针对其中的每一个目标。

瞄准TextFieldroot 相当于定位FormControl, since FormControl是“根”组件渲染者TextField https://github.com/mui-org/material-ui/blob/v4.4.2/packages/material-ui/src/TextField/TextField.js#L148.

瞄准方式没有区别Input, FilledInput, or OutlinedInput-- 他们都是通过InputProps.

作为旁注,使用className给定组件的 prop 也相当于classes.root.

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

import TextField from "@material-ui/core/TextField";
import { makeStyles } from "@material-ui/core/styles";
const useStyles = makeStyles({
  formControlRoot: {
    border: "2px solid lightgreen",
    padding: 2,
    marginTop: 10
  },
  inputRoot: {
    border: "2px solid blue"
  },
  inputLabelRoot: {
    border: "2px solid pink"
  },
  formHelperTextRoot: {
    border: "2px solid red"
  }
});

function App() {
  const classes = useStyles();
  const [variant, setVariant] = React.useState("standard");
  return (
    <div>
      <TextField
        variant={variant}
        label={`My Label (${variant})`}
        helperText="My Helper Text"
        classes={{ root: classes.formControlRoot }}
        InputProps={{ classes: { root: classes.inputRoot } }}
        InputLabelProps={{ classes: { root: classes.inputLabelRoot } }}
        FormHelperTextProps={{ classes: { root: classes.formHelperTextRoot } }}
      />
      <br />
      <br />
      <button onClick={() => setVariant("standard")}>Standard</button>
      <button onClick={() => setVariant("outlined")}>Outlined</button>
      <button onClick={() => setVariant("filled")}>Filled</button>
    </div>
  );
}

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

相关文档:https://material-ui.com/api/text-field/#props https://material-ui.com/api/text-field/#props

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

更改 MUI 文本字段的多个组件根 的相关文章

随机推荐