Как изменить цвет рамки Material-UI <textfield/"> - программирование
Подтвердить что ты не робот

Как изменить цвет рамки Material-UI <textfield/">

Я не могу понять, как изменить цвет контура выделенного варианта. Я посмотрел вокруг проблем GitHub, и люди, похоже, указывают на использование свойства "InputProps", но это, похоже, ничего не делает. This is the field Вот мой код в его текущем состоянии

import React from 'react';
import { withStyles } from '@material-ui/core/styles';
import TextField from '@material-ui/core/TextField';
import PropTypes from 'prop-types';

const styles = theme => ({
field: {
    marginLeft: theme.spacing.unit,
    marginRight: theme.spacing.unit,
    height: '30px !important'
},
});

class _Field extends React.Component {
      render() {
          const { classes, fieldProps } = this.props;
             return (
                <TextField
                {...fieldProps}
                label={this.props.label || "<Un-labeled>"}
                InputLabelProps={{ shrink: true }} // stop from animating.
                inputProps={{ className: classes.fieldInput }}
                className={classes.field}
                margin="dense"
               variant="outlined"
            />
        );
    }
}

_Field.propTypes = {
    label: PropTypes.string,
    fieldProps: PropTypes.object,
    classes: PropTypes.object.isRequired
}

export default withStyles(styles)(_Field);
4b9b3361

Ответ 1

Вы можете переопределить все имена классов, введенные Material-UI, благодаря свойству classes. Посмотрите на переопределение с разделом классов и реализацией компонента для более подробной информации.

и наконец:

Документация API компонента Input React. Подробнее о свойствах и точках настройки CSS.

Ответ 2

Взгляните на это, я сделал небольшую демонстрацию:

https://stackblitz.com/edit/material-ui-custom-outline-color

Он изменяет цвет границы по умолчанию и цвет метки TextField с пользовательским интерфейсом, но сохраняет основной цвет при фокусировке.

Кроме того, взгляните на эту ссылку, она дала мне "идею":

https://github.com/mui-org/material-ui/issues/13347

Если вы хотите изменить цвет в фокусе, посмотрите на эти примеры из документации:

https://material-ui.com/demos/text-fields/#customized-inputs

Ответ 3

const styles = theme => ({
  notchedOutline: {
    borderWidth: "1px",
    borderColor: "yellow !important"
  }
});

 <TextField
              variant="outlined"
              rows="10"
              fullWidth
              InputProps={{
                classes: {
                  notchedOutline: classes.notchedOutline
                }
              }}
              id="standard-textarea"
              label="Input Set"
              helperText="Enter an array with elemets seperated by , or enter a JSON object"
              placeholder="Placeholder"
              multiline
              value={"" + this.props.input}
              onChange={this.props.handleChangeValue("input")}
              className={classes.textField}
              margin="normal"
            />

enter image description here

Ответ 4

https://codesandbox.io/s/6rx8p

                      <CssTextField      

                       label="Username"

                       className="username"
                       name="username"
                       onChange={this.onChange}
                       type="text"
                       autoComplete="current-password"
                       margin="normal"
                       inputProps={{ style: { fontFamily: 'nunito', color: 'white'}}}

                    />

//объявляем const и добавляем стиль пользовательского интерфейса материала

const CssTextField = withStyles({
  root: {
   '& label.Mui-focused': {
    color: 'white',
   },
   '& .MuiInput-underline:after': {
    borderBottomColor: 'yellow',
   },
  '& .MuiOutlinedInput-root': {
    '& fieldset': {
      borderColor: 'white',
    },
    '&:hover fieldset': {
      borderColor: 'white',
    },
    '&.Mui-focused fieldset': {
      borderColor: 'yellow',
    },
  },
},

})(Текстовое поле);

Ответ 5

Расширяя ответ Петра. Вы также можете изменить все цвета событий без !important

 cssOutlinedInput: {
        "&:not(hover):not($disabled):not($cssFocused):not($error) $notchedOutline": {
          borderColor: "red" //default      
        },
        "&:hover:not($disabled):not($cssFocused):not($error) $notchedOutline": {
          borderColor: "blue" //hovered
        },
        "&$cssFocused $notchedOutline": {
          borderColor: "purple" //focused
        }
      },
      notchedOutline: {},
      cssFocused: {},
      error: {},
      disabled: {}

https://stackblitz.com/edit/material-ui-custom-outline-color-c6zqxp

Ответ 6

Я имею в виду, что Mui.TextField имеет 3 стиля: стандартный, заполненный, выделенный. Вышеупомянутое решение работает только в изложенном стиле

Ответ 7

  inputProps={{ style: { fontFamily: 'nunito', color: 'white'}}}

Inputprops работает путем стилизации введенных входных данных в текстовом поле, а также мы можем использовать className для пользовательской раскраски.

      const CssTextField = withStyles({
     root: {
    '& label.Mui-focused': {
     color: 'white',
      },
     '& .MuiInput-underline:after': {
      borderBottomColor: 'yellow',
     },
    '& .MuiOutlinedInput-root': {
     '& fieldset': {
     borderColor: 'white',
     },
     '&:hover fieldset': {
      borderColor: 'white',
       },
     '&.Mui-focused fieldset': {
       borderColor: 'yellow',
     },
     },
    },

Этот стиль const работает с внешним зельем поданного текста...

Оформление внешней части пользовательского интерфейса материала просили изменить...