2022 第51週 實作筆記:視覺效果一致的 TextField 與 FormControl 拼裝版 Input

總結

在將專案的 MaterialUI 版本從 4 升到 5 時,發現除了直接使用 TextField 以外,也可透過 FormControlInputFormHelperText 組合做出一致的視覺效果。

版本與環境

@mui/material: 5.11.0

筆記

元件部分

mui/material-ui/TextField.js 可以觀察到 TextField 會根據傳入的 props.variant 來決定最後要使用 InputFilledInputOutlinedInput 元件:

const variantComponent = {
  standard: Input,
  filled: FilledInput,
  outlined: OutlinedInput,
};

而原始碼下方的 return 部位也可觀察到 TextField 是根據 helperText 的有無來判定是否要顯示 FormHelperText 元件:

{
  helperText && (
    <FormHelperText id={helperTextId} {...FormHelperTextProps}>
      {helperText}
    </FormHelperText>
  );
}

單純以視覺效果來說,以下兩者可以做出一致效果,但須注意 FormControl 拼裝版需自行設定 idhtmlForaria-describedby

JavaScript syntax

在原始碼中發現還有以下寫法,解構賦值的同時使用冒號來將值賦予新的變數:

const {
  // ...
  id: idOverride,
  // ...
} = props;

白話文:將 props.id 的值賦予到本地變數 idOverride 中。

MDN: A property can be unpacked from an object and assigned to a variable with a different name than the object property.

const o = { p: 42, q: true };
const { p: foo, q: bar } = o;

console.log(foo); // 42
console.log(bar); // true

MDN: Here, for example, const { p: foo } = o takes from the object o the property named p and assigns it to a local variable named foo.

參考文件