简体   繁体   中英

In Material UI, how can I change the border color of the TextField only after the user enters text?

Given a TextField , is there a way I can detect that it has text input, and then style the border only on that condition?

I'm using the outlined TextField . It has placeholder text when empty.

<TextField variant="outlined" />

Currently I've only succeeded in changing the text input color when it's filled by detecting if there's placeholder text currently visible.

In my overrides:

MuiOutlinedInput: {
  root: {
    '& $notchedOutline': {
      borderColor: 'green', // default colour, want to change this when field has input
    },
  },
  input: {
    '&:not(:placeholder-shown)': {
      color: 'red', // input field text becomes red when input is provided
    },
  },
},

Code Sandbox

I want the border to also become red here when the user enters text. I can't get the placeholder trick to work on changing the border color because the border by default is on the <fieldset> not the <input> . Does anyone have any ideas?

Because CSS has no pseudo selector to detect whether input is empty or not ( this question ), so you must programmatically detect input and override the TextField border color

<TextField
  id="fullName"
  placeholder="Full name"
  variant="outlined"
  value={this.state.inputValue}
  onChange={(e) => this.setState({ inputValue: e.target.value })}
  InputProps={{
    classes: {
      notchedOutline: this.state.inputValue && classes.greenBorder
    }
  }}
/>

Codesandbox for demo

编辑 material-ui 文本字段(分叉)

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