warning: React does not recognize the xxx prop on a DOM element
欢迎使用Markdown编辑器
1、错误提示
Warning: React does not recognize the disableValue prop on a DOM element. If you intentionally want it to appear in the DOM as a custom attribute, spell it as lowercase disablevalue instead. If you accidentally passed it from a parent component, remove it from the DOM element
2、分析原因
这是React不能识别dom元素上的非标准attribute报出的警告,最终的渲染结果中React会移除这些非标准的attribute。
const MyCheckboxGroup: React.FC<MyCheckboxGroupProps> = props => {
const { data, value, onChange, style, disableValue } = props;
useEffect(()=>{
onChange?.(value);
}, [value])
return (
<Checkbox.Group
{...props}
value={value}
onChange={ onChange}
style={style || {}}
>
{Object.getOwnPropertyNames(data).map((item: any, index: any) => (
<Checkbox value={Number.parseInt(item, 10).toString()} style={{ marginLeft: 0 }} disabled={disableValue?.includes(item)} key={index}>
{
typeof data[item] === 'string'
? data[item]
: data[item]?.text
}
</Checkbox>
))}
</Checkbox.Group>
);
};
3、解决
可以使用other接收属性参数,仅将other属性参数传递给子组件或对应的dom,自定义属性只组件自己使用。
const MyCheckboxGroup: React.FC<MyCheckboxGroupProps> = props => {
const { data, value, onChange, style, disableValue, ...other } = props;
useEffect(()=>{
onChange?.(value);
}, [value])
return (
<Checkbox.Group
{...other}
value={value}
onChange={ onChange}
style={style || {}}
>
{Object.getOwnPropertyNames(data).map((item: any, index: any) => (
<Checkbox value={Number.parseInt(item, 10).toString()} style={{ marginLeft: 0 }} disabled={disableValue?.includes(item)} key={index}>
{
typeof data[item] === 'string'
? data[item]
: data[item]?.text
}
</Checkbox>
))}
</Checkbox.Group>
);
文章讲述了在React应用中遇到的关于不识别DOM元素上非标准属性的警告,分析了原因在于使用了非标准的attribute。解决方案是通过提取其他属性并仅将它们传递给子组件,以避免React移除这些属性。示例代码展示了如何修改以避免此类警告。

2102

被折叠的 条评论
为什么被折叠?



