尝试从material-ui中限制TextField并接收inputRef错误



我目前正试图限制我的项目中的自动完成文本字段,但每当我使用InputProps={{ maxLength: 2 }}时,它就会吐出一个错误,说我的inputRef.current is null,但我已经使用React.createRef();设置了inputRefprop中的ref,它仍然给我一个错误,通过console.log(inputRef)它实际上向我展示了ref被设置为的正确元素。

我用这个来创建这个函数在我点击它的时候聚焦元素

const inputRef = React.createRef();
const focusOnClick = () => {
inputRef.current.focus();
};

这是自动完成功能所在的组件。

<Uf
id="Uf"
name="uf"
label="UF"
value="SP"
onClick={focusOnClick}
inputRef={inputRef}
inputProps={{ maxLength: 2 }}
fullWidth
/>

这是自动补全,{...importedProps}是所有通过第一个组件传递到这里的Props

<Autocomplete
options={ufList}
getOptionLabel={(option) => option.label}
style={{ width: 200, marginLeft: 10 }}
onChange={changeValue}
getOptionSelected={(option) => option.value === value}
className={clsx(classes.TextField, classes.dense)}
// value={value}
autoHighlight
autoSelect
renderInput={(params) => (
<TextField
{...params}
{...importedProps}
error={Boolean(errorMessage)}
helperText={errorMessage}
label="UF"
value={value}
margin="dense"
variant="outlined"
/>
)}
/>
  1. 要专注于您的TextField,您只需使用autoFocus属性,而不必使用onClick

  2. 如果你仍然想做onClick尝试使用useRef钩子代替。

  3. 我很确定你遇到了一个错误,因为你试图使用inputRef={inputRef}在你的<Uf/>组件,不是一个材料- ui组件。如果您想要关注TextField组件,则将inputRef={inputRef}移动到TextField中。如果你仍然想引用Uf-试着将inputRef重命名为ref


也就是说:使用inputRef与输入类型材质- ui组件,使用ref


  1. 当涉及到你的字符串长度限制时,你的代码应该工作得很好。

最新更新