简体   繁体   中英

How can I center-align Material-ui TextField text and also set a min number value?

I am trying to both center align the text inside and set a min number value to 0. But that is not occurring. I can do either or but not both at the same time. I looked at the material-ui page on TextField but it was no help --> here

<TextField type="number" 
    id={cells.id} 
    inputProps={{min: 0}} 
    InputProps={classes.inputText}  
    className={classes.inputComponent} 
    disabled={cells.disabled} 
    defaultValue={cells.text} />

I need to set a style for the text field itself and style for the text inside.

inputComponent: {
    height: '30px',
    width:  '71px',
    border: '1px solid #D3D4D0',
    borderRadius: '5px',
    backgroundColor: '#FFFFFF',
    boxShadow: '0 1px 0 0 rgba(170,170,170,0.01)'
}

inputText: {
    color: 'rgba(0,0,0,0.87)',
    fontSize: '16px',
    letterSpacing: '0.5px',
    lineHeight: '28px',
    textAlign: 'center',
}

Change JSX a little:

<TextField type="number" 
    id={cells.id} 
    inputProps={{min: 0, style: { textAlign: 'center' }}} // the change is here
    InputProps={classes.inputText}  
    className={classes.inputComponent} 
    disabled={cells.disabled} 
    defaultValue={cells.text} />

Reason

InputStyle is not part of the API anymore.

You need to use it as style: {} inside inputProps the same way as InputStyle before.

For MUI v5:

<TextField
  sx={{input: {textAlign: "center"}}}
/>

UPDATE Material UI 5

With the new version of Material UI, the inputProps is one level deeper.

<TextField 
    InputProps={{
        inputProps: {
            style: { textAlign: "right" },
        }
    }}
/>

for right-align

    import { styled } from '@mui/material/styles';
    const useStyles = makeStyles({
    input: {
      "& .css-1t8l2tu-MuiInputBase-input-MuiOutlinedInput-input": {
        textAlign: 'right',
      },
       "& .css-1d3z3hw-MuiOutlinedInput-notchedOutline": {
           textAlign: 'right'
       },

       "& .css-1kty9di-MuiFormLabel-root-MuiInputLabel-root": {
           transformOrigin: 'top left' ,
           left: 'auto',
           right: 8,
       },

       "& .css-14s5rfu-MuiFormLabel-root-MuiInputLabel-root" :{
           left: 'auto',
           right: 20,
       }
    }
  })

and then

    function ComponentNam (){ 
        const classes = useStyles();
        return(
         <TextField className={classes.input} fullWidth label="کلمه را وارد
          کنید" id="fullWidth" /> 
        )
     }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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