簡體   English   中英

在 Material UI 中,如何僅在用戶輸入文本后更改 TextField 的邊框顏色?

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

給定一個TextField ,有沒有一種方法可以檢測到它有文本輸入,然后僅在該條件下設置邊框樣式?

我正在使用概述的TextField 為空時它有占位符文本。

<TextField variant="outlined" />

目前,我只通過檢測當前是否有占位符文本來成功更改文本輸入顏色。

在我的覆蓋中:

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
    },
  },
},

代碼沙盒

當用戶輸入文本時,我希望邊框在這里也變成紅色。 我無法使用占位符技巧來更改邊框顏色,因為默認情況下邊框位於<fieldset>而不是<input>上。 有人有什么想法嗎?

因為 CSS 沒有偽選擇器來檢測輸入是否為空( 這個問題),所以你必須以編程方式檢測輸入並覆蓋 TextField 邊框顏色

<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

編輯 material-ui 文本字段(分叉)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM