Warning: React does not recognize the X prop on a DOM element

297 阅读1分钟

Warning: React does not recognize the X prop on a DOM element

在使用 react的时候可能会遇到如下报错: image.png image.png

解决方法

class Parent extends React.Component<any, any> {
    //...代码
    render(): React.ReactNode {
        const { prefixCls, className, ...props } = this.props;
        return <Child {...props} />;
    }
}
class Child extends React.Component<any, any> {
    //...代码
    render(): React.ReactNode {
        return <div {...props} />;
    }
}

当外部调用 Parent 组件时,可能给组件传了很多参数,然后通过{...props}传递给了子组件,在上方示例中,{...props}最终传到了div组件里,但是div组件里并没有自定义的属性,比如上方图片中的faq。所以会报错. 修复方式:

class Parent extends React.Component<any, any> {
    //...代码
    render(): React.ReactNode {
        const { prefixCls, className, faq, ...props } = this.props;
        return <Child {...props} />;
    }
}

将属性从{...props}中移除,就不会传递到DOM 元素上产生错误。