简体   繁体   English

设置 TextField 高度 material-ui

[英]Set TextField height material-ui

index.js索引.js

import React from 'react'
import TextField from '@material-ui/core/TextField'
import style from './style'
import withStyles from 'hoc/withStyles'
import { connect } from 'react-redux'

class SearchField extends React.Component {
  constructor (props) {
    super(props)
    this.onChange = this.onChange.bind(this)
  }

  onChange (event) {
    const { dispatcher } = this.props
    this.props.dispatch(dispatcher(event.target.value))
    event.preventDefault()
  }

  render () {
    const { classes, placeholder } = this.props
    return (
      <TextField 
        label={placeholder} 
        placeholder={placeholder}
        InputProps={{ classes: { input: classes.resize } }}
        className={classes.textField}
        margin="normal"
        autoFocus={true} 
        variant="outlined" 
        onChange={this.onChange}
      />
    )
  }
}

export default withStyles(style)(connect()(SearchField))

style.js样式.js

export default function () {
  return {
    container: {
      display: 'flex',
      flexWrap: 'wrap'
    },
    textField: {
      width: 'auto'
    },
    resize: {
      fontSize: 11
    }
  }
}

https://material-ui.com/api/text-field/ https://material-ui.com/api/text-field/

How can I change TextField height?如何更改TextField高度? I can't find it in the documentation.我在文档中找不到它。 When I try to change it directly in CSS it works incorrectly (it looks like this - selected height on the screen 26px).当我尝试在 CSS 中直接更改它时,它无法正常工作(看起来像这样- 在屏幕上选择的高度为 26px)。

What should I do?我应该怎么办?

您可以尝试添加 Textfield API 中提到的 size="small"

<TextField variant="outlined" size="small" / >

The other answer is useful but didn't work for me because if a label is used in an outlined component (as it is in the question) it leaves the label uncentered.另一个答案很有用,但对我不起作用,因为如果在outlined组件中使用label (如问题中所示),它会使label居中。 If this is your usecase, read on.如果这是您的用例,请继续阅读。

The way the <label> component is styled is somewhat idiosyncratic, using position: absolute and transform . <label>组件的样式有点特殊,使用position: absolutetransform I believe it's done this way to make the animation work when you focus the field.我相信这样做是为了在您专注于该领域时使动画工作。

The following worked for me, with the latest material-ui v4 (it should work fine with v3 too).以下对我有用,使用最新的 material-ui v4 (它也适用于v3 )。

// height of the TextField
const height = 44

// magic number which must be set appropriately for height
const labelOffset = -6

// get this from your form library, for instance in
// react-final-form it's fieldProps.meta.active
// or provide it yourself - see notes below
const focused = ???

---

<TextField
  label="Example"
  variant="outlined"

  /* styles the wrapper */
  style={{ height }}

  /* styles the label component */
  InputLabelProps={{
    style: {
      height,
      ...(!focused && { top: `${labelOffset}px` }),
    },
  }}

  /* styles the input component */
  inputProps={{
      style: {
        height,
        padding: '0 14px',
      },
  }}
/>

Notes笔记

  • I just used inline styles rather than the withStyles HOC, as this approach just seems simpler to me我只是使用内联样式而不是withStyles HOC,因为这种方法对我来说似乎更简单
  • The focused variable is required for this solution - you get this with final-form , formik and probably other form libraries.focused变量需要这种解决方案-你得到这个与final-formformik大概其他形式的库。 If you're just using a raw TextField , or another form library that doesn't support this, you'll have to hook this up yourself.如果您只是使用原始TextField或其他不支持此功能的表单库,则您必须自己连接它。
  • The solution relies on a magic number labelOffset to center the label which is coupled to the static height you choose.该解决方案依赖于一个幻数labelOffset来使与您选择的静态height耦合的label居中。 If you want to edit height , you'll also have to edit labelOffset appropriately.如果您想编辑height ,您还必须适当地编辑labelOffset
  • This solution does not support changing the label font size.此解决方案支持更改标签字体大小。 You can change the input font size, only if you're fine with there being a mismatch between that and the label.您可以更改输入字体大小,前提是您认为输入字体大小与标签不匹配。 The issue is that the size of the 'notch' that houses the label in the outlined border is calculated in javascript according to a magic number ratio that only works when the label font size is the default.问题在于,在 javascript 中根据一个幻数比率计算在轮廓边框中放置标签的“缺口”的大小,该比率仅在标签字体大小为默认值时才有效。 If you set the label font size smaller, the notch will also be too small when the label shows in the border.如果您将标签字体设置得更小,那么当标签显示在边框中时,凹口也会太小。 There's no easy way to override this, short of repeating the entire calculation yourself and setting the width of the notch (the component is fieldset > legend ) yourself via CSS.没有简单的方法可以覆盖它,除了自己重复整个计算并通过 CSS 自己设置槽口的宽度(组件是fieldset > legend )。 For me this wasn't worth it, as I'm fine with using the default font sizes with a height of 44px.对我来说这不值得,因为我可以使用高度为 44px 的默认字体大小。

You didn't show how you tried to specify the height, but the approach you used for font-size is the right approach.您没有展示如何尝试指定高度,但是您用于 font-size 的方法是正确的方法。 Here's an example showing two text fields with different heights:这是一个示例,显示了具有不同高度的两个文本字段:

import React from "react";
import ReactDOM from "react-dom";
import TextField from "@material-ui/core/TextField";
import { withStyles } from "@material-ui/core/styles";
const styles = {
  input1: {
    height: 50
  },
  input2: {
    height: 200,
    fontSize: "3em"
  }
};
function App(props) {
  return (
    <div className="App">
      <TextField
        variant="outlined"
        InputProps={{ classes: { input: props.classes.input1 } }}
      />
      <TextField
        variant="outlined"
        InputProps={{ classes: { input: props.classes.input2 } }}
      />
    </div>
  );
}
const StyledApp = withStyles(styles)(App);
const rootElement = document.getElementById("root");
ReactDOM.render(<StyledApp />, rootElement);

And here is a code sandbox with the same code so you can see it running.这是一个具有相同代码的代码沙箱,因此您可以看到它正在运行。

The component takes a multiline prop which is a boolean.该组件采用一个布尔值的multiline属性。 Set this to true, and then set the component's rows prop to a number.将此设置为 true,然后将组件的rows属性设置为一个数字。

   <TextField
      multiline={true}
      rows={3}
      name="Description"
      label="Description"
      placeholder="Description"
      autoComplete="off"
      variant="outlined"
      value={description}
      onChange={e => setDescription(e.target.value)}
    />

This works with material-ui v3,这适用于 material-ui v3,

<div className="container">
  <TextField
    label="Full name"
    margin="dense"
    variant="outlined"
    autoFocus
  />
</div>

.css .css

.container input {
  height: 36px;
  padding: 0px 14px;
}

.container label {
  height: 36px;
  top: -6px;
}

.container label[data-shrink="true"] {
  top: 0;
}

https://codesandbox.io/s/elated-kilby-9s3ge https://codesandbox.io/s/elated-kilby-9s3ge

With material-ui v4+, you have to adjust the input padding and the label position to get what you whant.使用 material-ui v4+,您必须调整输入填充和标签位置才能得到您想要的。

<TextField label="Label" variant="outlined" />

Suppose we want the above TextField to be 48px height (it's default size is 56px), we just have to do (56px - 48px) / 2 = 4px and in our css file:假设我们希望上面的 TextField 高度为 48px(默认大小为 56px),我们只需要在我们的 css 文件中执行 (56px - 48px) / 2 = 4px :

.MuiTextField-root input {
  /* 14.5px = 18.5px - 4px (note: 18.5px is the input's default padding top and bottom) */
  padding-top: 14.5px;
  padding-bottom: 14.5px; 
}

.MuiTextField-root label {
  top: -4px;
}

.MuiTextField-root label[data-shrink='true'] {
  top: 0;
}

For styled-components users, all the above block of code can be defined as Sass mixins that can be re-used throughout the code base对于样式组件用户,所有上述代码块都可以定义为可以在整个代码库中重复使用的Sass mixins

import { css } from 'styled-components'

const muiTextFieldHeight = (height: number) => {
  const offset = (56 - height) / 2

  return css`
    input {
      padding-top: calc(18.5px - ${offset}px);
      padding-bottom: calc(18.5px - ${offset}px);
    }

    label {
      top: -${offset}px;
    }

    label[data-shrink='true'] {
      top: 0;
    }
  `
}

Then somewhere in your stylesheet然后在你的样式表中的某个地方

  .MuiTextField-root {
      ${muiTextFieldHeight(40)} /* set TextField height to 40px */
  }

要使其更窄,请设置高度,并在 TextField 上添加“密集”边距道具以保持标签正确对齐:

<TextField margin="dense" style={{ height: 38 }} />

First of all, my heart goes out to any poor soul in this thread who has found themselves fighting against the awkward design of the MUI components.首先,我的心与这个线程中的任何可怜的灵魂同在,他们发现自己与 MUI 组件的笨拙设计作斗争。 Second, if you're using themes AND the "filled" variant of TextField, this solution might work for you.其次,如果您使用主题和 TextField 的“填充”变体,则此解决方案可能适合您。 Using the Chrome Dev Tools, I found success adjusting the height of the divs with the classes "MuiFormControl-root" and "MuiInputBase-root".使用 Chrome 开发工具,我发现使用“MuiFormControl-root”和“MuiInputBase-root”类调整 div 的高度是成功的。 This is what my code looks like (results may vary):这是我的代码的样子(结果可能会有所不同):

const theme = createMuiTheme({
  overrides: {
    MuiFormControl: {
      root: {
        height: '56px',
      },
    },
    MuiInputBase: {
      root: {
        height: '56px',
      },
    },
  },
})

Changing the height is simple, can be achieved using改变高度很简单,可以使用

InputProps={{style: { fontSize: '1.8rem', height: 70 },

But that isn't enough, because the label(placeholder in this case) will not be centered.但这还不够,因为标签(在本例中为占位符)不会居中。 Label can be centered using: Label 可以使用以下方法居中:

sx={{'.MuiFormLabel-root[data-shrink=false]': { top: <put desired value here>} }}

With React and "@mui/material": "^5.2.2",使用 React 和"@mui/material": "^5.2.2",

import * as React from 'react';
import TextField from '@mui/material/TextField';

export default function BasicTextFields() {
  return (
    <TextField
      label="Outlined"
      variant="outlined"
      InputLabelProps={{
        style: {
          fontSize: 14,
          backgroundColor: '#FFF',
          paddingLeft: 4,
          paddingRight: 4,
          color: '#383838',
        },
      }}
      inputProps={{
        style: {
          fontSize: 14,
          height: 40,
          width: 272,
          padding: '0 14px',
          fontWeight: 'bold'
        },
    }}
    />
  );
}

CSS CSS

.MuiTextField-root{
  border: 1px solid $BORDER_COLOR_2;
  border-radius: 6px;
  height: 40px;
  box-shadow: 0px 2px 3px $BOX_SHADOW_1;
  color: $TEXT_COLOR_3;
  font-size: 14px;
  font-weight: bold;
}

.MuiTextField-root label {
  top: -6px;
}

.MuiTextField-root label[data-shrink='true'] {
  top: 0;
}
  <TextField
    id="outlined-multiline-static"
    label="Multiline"
    multiline
    fullWidth
    defaultValue="Default Value"
    inputProps={{
      style: {
        height: "600px",
      },
    }}
  />

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM