【问题标题】:Material-UI Autocomplete is not working when setting TextField InputProps设置 TextField InputProps 时,Material-UI 自动完成功能不起作用
【发布时间】:2020-07-29 00:23:36
【问题描述】:

我正在使用Material-UI Autcomplete 组件(免费独奏 版本)并且一切正常,直到我尝试更改文本的颜色(在TextField 内)。

我的代码如下所示:

const moreClasses = {
    label: { style: { color: 'blue' } },
    input: {
        style: {
            color: 'red',
            borderBottom: `1px solid green`
        }
    }
};
//...
<Autocomplete
    //... classic props as in the official Doc
    renderInput={params => <TextField 
        {...params} 
        label={'label'} 
        InputLabelProps={moreClasses.label}
        InputProps={moreClasses.input} />
/>

预期行为

当您开始输入时,您可以看到自动完成,并且您输入的文本应该是红色的。

实际行为

文本颜色为红色,但自动完成功能不再起作用。

我创建了this live running example 来说明 3 个组件的问题:

  • 仅限文本字段(有效)

  • 使用InputProps 不改变颜色的自动完成功能(有效)

  • 使用 InputProps 更改颜色的自动完成功能(不起作用)

注意

通过设置InputLabelProps,自动完成功能继续工作并且标签的颜色发生了变化(在我分享的示例中为蓝色)!所以我无法弄清楚为什么设置InputProps时它不起作用。

对此问题有何反馈?

【问题讨论】:

    标签: reactjs material-ui


    【解决方案1】:

    传递InputProps 会导致问题,因为Autocomplete 组件passes InputProps 作为params 的一部分传递给TextField,因此显式传递的InputProps 将完全替换params 中的InputProps

    您可以通过将params.InputProps 与附加的InputProps 组合来解决此问题,例如以下代码:

    InputProps={{ ...params.InputProps, ...moreClasses.input }}
    

    Autocomplete 也有 passes InputLabelProps,所以即使它不明显地闯入,你也应该对 InputLabelProps 做同样的事情:

    InputLabelProps={{ ...params.InputLabelProps, ...moreClasses.label }}
    

    相关回答:Setting text color, outline, and padding on Material-ui Autocomplete component

    【讨论】:

    • 是的,通过将我的额外 InputProps 与 params.InputProps 结合起来解决了问题,正如你所描述的。谢谢
    • @AlaEddineJEBALI 注意我对InputLabelProps 的补充——你需要为它做同样的事情,否则某些可访问性方面会被破坏。
    猜你喜欢
    • 2021-03-18
    • 2021-05-05
    • 2015-08-22
    • 1970-01-01
    • 1970-01-01
    • 2018-06-26
    • 2018-07-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多