【问题标题】:Change TextField (MUI) background color when data present数据存在时更改 TextField (MUI) 背景颜色
【发布时间】:2021-12-31 18:11:59
【问题描述】:

使用 'styled' MUI 组件和主题,创建了一个 TextField 组件。

当 TextField 没有数据(即为空)时,使用以下样式将背景渲染为自定义灰色:

'& .MuiInputBase-root': {
  backgroundColor: theme.palette.background.grey01,
  height: '40px'
},

当数据被输入到 TextField 时,这个 backgroundColor 需要改变(变成白色)。不仅是“聚焦”,而且如果存在数据(即 TextField 不为空),则白色背景必须保持不变;但是,如果用户删除/移除数据(即 TextField 被用户清空),backgroundColor 需要回到 custom-grey。

通过 Chrome Inspect,能够追踪相关类(包括 .Mui-focused):

MuiOutlinedInput-root MuiInputBase-root MuiInputBase-colorPrimary Mui-Focused MuiInputBase-formControl css-1byr8j2-MuiInputBase-root-MuiOutlinedInput-root

已查看 https://mui.com/customization/how-to-customize/#use-rulename-to-reference-a-local-rule-within-the-same-style-sheet 上的 MUI 文档,但无法确定一种方法来了解值何时填充/为空。

【问题讨论】:

    标签: material-ui textfield styled-components


    【解决方案1】:

    更新:

    我忽略了最简单、最优雅的解决方案。

    const StyledTextField = styled(TextField)`
      .MuiInputBase-root {
        background-color: ${({theme, value}) => 
          !value && theme.palette.background.grey01};
      }
    `
    

    【讨论】:

    • 太棒了。谢谢你。该组件已经收到“价值”作为道具。因此,能够使用 value.length 来确定 backgroundColor 是灰色还是白色。而且,它有效!
    • @jsN00b 完美!对不起,我有点不喜欢 SC,但很高兴能帮上忙! ?
    猜你喜欢
    • 1970-01-01
    • 2022-10-16
    • 2019-12-23
    • 1970-01-01
    • 2021-12-22
    • 1970-01-01
    • 2022-10-22
    • 2021-08-18
    • 1970-01-01
    相关资源
    最近更新 更多