programing

TextField 높이 재료 UI 설정

lovejava 2023. 3. 25. 09:11

TextField 높이 재료 UI 설정

index.displaces를 표시합니다.

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.displaces를 선택합니다.

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

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

어떻게 하면 바꿀 수 있을까?TextField높이?서류상으로는 찾을 수 없습니다.CSS에서 직접 변경하려고 하면 올바르게 동작하지 않습니다(화면 26px에서 선택한 높이와 같습니다).

어떻게 해야 하나?

Textfield API에 기재되어 있는 size="small"을 추가할 수 있습니다.

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

다른 답변은 유용하지만 나에게는 효과가 없었다.label에 사용됩니다.outlined컴포넌트(질문에 기재되어 있는 바와 같이)는 이 컴포넌트로부터label중심적이지 않은이것이 유스케이스인 경우는, 계속 읽어 주세요.

그 방법<label>스타일링된 컴포넌트는 다소 특이합니다.position: absolute그리고.transform이렇게 하면 이 분야에 집중해서 애니메이션을 할 수 있을 것 같습니다.

최신 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',
      },
  }}
/>

메모들

  • 그냥 인라인 스타일만 썼는데withStylesHOC, 이 접근방식은 단순하다고 생각되기 때문에
  • focused이 솔루션에는 변수가 필요합니다.이거는final-form,formik아마 다른 형태의 라이브러리도 있을 겁니다.날것만 사용한다면TextField또는 이 기능을 지원하지 않는 다른 양식 라이브러리를 직접 연결해야 합니다.
  • 솔루션은 매직넘버에 의존합니다.labelOffset중심을 잡다label정전기와의 결합으로height선택해주세요.편집하고 싶은 경우height, 편집도 필요합니다.labelOffset적당하게.
  • 솔루션은 라벨 글꼴 크기 변경을 지원하지 않습니다.입력 글꼴 크기는 라벨과 일치하지 않는 경우에만 변경할 수 있습니다.문제는 레이블 글꼴 크기가 기본일 때만 작동하는 매직 넘버 비율에 따라 레이블이 윤곽선에 있는 '노치'의 크기가 Javascript로 계산된다는 것입니다.레이블 글꼴 크기를 작게 설정하면 레이블이 테두리에 표시될 때 노치가 너무 작습니다.전체 계산을 직접 반복하고 노치의 너비를 설정하는 것 이외에는 이를 무시할 수 있는 쉬운 방법이 없습니다(컴포넌트는fieldset>legend)를 참조해 주세요.높이가 44px인 기본 글꼴 크기를 사용해도 괜찮기 때문에, 이것은 저에게 가치가 없었습니다.

는 「」를 합니다.multiline부울형 지주true로 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)}
    />

높이를 지정하는 방법을 보여주지 않았지만 글꼴 크기에 사용한 방법이 올바른 방법입니다.높이가 다른 두 개의 텍스트 필드를 표시하는 예를 다음에 나타냅니다.

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);

그리고 여기 같은 코드를 가진 코드 샌드박스가 있습니다.이것이 동작하는 것을 볼 수 있습니다.

우선, 저는 MUI 부품의 어색한 디자인에 맞서 싸우고 있는 이 실의 불쌍한 영혼에게 마음이 갑니다.둘째, 테마와 TextField의 "채운" 버전을 사용하는 경우 이 솔루션이 효과적일 수 있습니다.Chrome Dev Tools를 사용하여 "MuiFormControl-root" 및 "MuiInputBase-root" 클래스로 디바의 높이를 조정하는 데 성공했습니다.코드는 다음과 같습니다(결과는 다를 수 있습니다).

const theme = createMuiTheme({
  overrides: {
    MuiFormControl: {
      root: {
        height: '56px',
      },
    },
    MuiInputBase: {
      root: {
        height: '56px',
      },
    },
  },
})
  <TextField
    id="outlined-multiline-static"
    label="Multiline"
    multiline
    fullWidth
    defaultValue="Default Value"
    inputProps={{
      style: {
        height: "600px",
      },
    }}
  />

레이블을 좁히려면 높이를 설정하고 레이블이 올바르게 정렬되도록 텍스트 필드에 "밀도" 여백 받침대를 추가합니다.

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

material-ui v4+에서는 원하는 것을 얻기 위해 입력 패딩과 라벨 위치를 조정해야 합니다.

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

위의 TextField의 높이를 48px(기본 크기는 56px)로 하려면 (56px - 48px) / 2 = 4px 및 css 파일로 해야 합니다.

.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;
}

스타일 컴포넌트 사용자의 경우 위의 모든 코드 블록을 코드 베이스 전체에서 재사용할 수 있는 Sas mixin으로 정의할 수 있습니다.

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;
    }
  `
}

그럼 스타일시트 어딘가에

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

이것은 material-ui v3에서 동작합니다.

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

.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

및 ★★★★★★"@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

.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;
}

높이 변경은 간단하며 다음을 사용하여 수행할 수 있습니다.

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

그러나 레이블(이 경우 자리 표시자)이 중앙에 배치되지 않기 때문에 충분하지 않습니다.라벨은 다음 방법으로 중앙에 배치할 수 있습니다.

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

언급URL : https://stackoverflow.com/questions/53854030/set-textfield-height-material-ui