React报错:无法识别DOM元素上的`InputProps`属性该如何解决?
这个警告的本质是大写开头的InputProps属性被传递给了原生DOM元素,而DOM规范里没有这个属性,React才会抛出提示。对于MUI的TextField组件来说,它本身是支持InputProps属性的,出现这个报错大概率是你展开的属性对象里携带了多余的InputProps字段。
解决方案
- 第一步:检查你展开的
{...input}和{...rest}两个对象中是否包含InputProps键。你可以在组件渲染前打印这两个对象的所有属性,如果确实包含InputProps,需要先将该字段从这两个对象中剔除再展开,避免直接透传给TextField的根DOM节点。 - 第二步:如果需要保留从
input或rest中拿到的InputProps配置,可以将它和你代码中现有的InputProps合并,示例如下:
// 先剔除多余字段 const { InputProps: inputInputProps, ...cleanInput } = input; const { InputProps: restInputProps, ...cleanRest } = rest; // 组件中合并传入 <TextField {...cleanInput} {...cleanRest} inputRef={inputRef} autoFocus={inputRef.current === document.activeElement} disabled={!!disabled} multiline={!!rowCount} style={{ width: "100%", }} onChange={(event) => { input.onChange(event.target.value); }} {...(hesapla ? { onBlur: (e) => { hesapla({ name: input.name, value: input.value }); }, onKeyDown: (e) => { if (e.key === "Enter") { hesapla({ name: input.name, value: input.value }); e.preventDefault(); } }, } : {})} InputProps={{ classes, ...inputInputProps, ...restInputProps, ...(inputComponent ? { inputComponent } : {}), ...(endAdornment ? { endAdornment } : {}), }} inputProps={{ style: { maxHeight: (rowCount * 16).toString() + "px", overflow: "auto", ...(rightJustify ? { textAlign: "end" } : {}), ...(!readOnly && hesapla ? { fontWeight: "bold", borderBottom: "2px solid" } : {}), }, readOnly: !!readOnly, }} ></TextField>
- 额外优化:你原有代码中存在冗余属性赋值,比如已经展开
{...input}的前提下又单独写了name={input.name},布尔类属性也可以用!!简化写法,清理这类冗余代码可以避免潜在的属性覆盖冲突。
内容的提问来源于stack exchange,提问作者Mümin ZEHİR
相关产品推荐
相关产品推荐

