繁体   English   中英

如何使 MUI 自动完成只读?

[英]How to make the MUI Autocomplete read only?

使用@mui/material/Autocomplete ,我无法终生将组件设为只读!

即使renderInput function 返回一个<TextField readOnly />组件,下拉菜单仍然会触发onChange事件。

我尝试了<Autocomplete readOnly /> ,但该属性被忽略了。

这似乎是一个粗略的设计疏忽,还是我遗漏了什么? 并非所有组件都支持相同的属性。

目前,我发现使用disabled而不是readOnly会产生所需的结果,但这会产生非统一的形式; 某些字段是只读的,其他字段是禁用的。


** 编辑 **

那些发现这个问题的人应该支持并关注 Github 上的持续问题


** 解决方案 **

这是我使用的工作解决方案:

import React, { forwardRef, useState } from 'react';
import PropType from 'prop-types';

import Autocomplete from '@mui/material/Autocomplete';

const AutocompleteEx = forwardRef(({
   readOnly,
   renderInput,
   ...props
}, ref) => {
   const [open, setOpen] = useState(false);
   
   return (
      <Autocomplete ref={ ref }
         open={ open }
         onOpen={ () => !readOnly && setOpen(true) }
         onClose={ () => setOpen(false) }
         disableClearable={ readOnly }
         renderInput={ ({ inputProps, ...params }) => renderInput({ ...params, inputProps: { readOnly, ...inputProps } }) }
         { ...props }
      />
   );
});
AutocompleteEx.propTypes = {
   readOnly: PropType.bool,
   renderInput: PropType.func.isRequired
};
AutocompleteEx.defaultProps = {
   readOnly: false
};

export default AutocompleteEx

v5.4.0 版本中,MUI 添加了一个readOnly属性,可以直接传递给Autocomplete组件:

<Autocomplete readOnly {...yourOtherProps} />

如果Autocomplete是只读的,您可以控制open的 state 并停止打开下拉菜单:

const [open, setOpen] = React.useState(false);
const [readOnly, setReadOnly] = React.useState(false);

return (
  <>
    <Button onClick={() => setReadOnly((o) => !o)}>toggle readonly</Button>
    <Autocomplete
      options={top100Films}
      open={open}
      onOpen={() => !readOnly && setOpen(true)}
      onClose={() => setOpen(false)}
      disableClearable={readOnly}
      renderInput={(params) => (
        <TextField
          {...params}
          InputProps={{ ...params.InputProps, readOnly }}
          label="Movie"
        />
      )}
    />
  </>
);

现场演示

Codesandbox 演示

简单的解决方案可能是: - 只需添加readOnly={Boolean}作为道具。

附上工作样本

 <Autocomplete
    autoComplete
    id='combo-box-demo'
    options={allCities}
    getOptionLabel={(option) => {
      return option?.name;
    }}
    openOnFocus
    readOnly={!isEditable}
    includeInputInList
/>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM