警告:React 无法识别 DOM 元素上的 `warnKey` 属性

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

我正在使用 testing-library/react 进行路由单元测试 下面是我的代码 我的测试用例通过了,但我收到

的控制台错误

React 无法识别 DOM 元素上的 warnKey 属性。

有什么想法吗?下面是我的代码和错误截图

import {render, screen} from '@testing-library/react'
import {createMemoryHistory} from 'history'
import React from 'react'
import {Router} from 'react-router-dom'
import '@testing-library/jest-dom/extend-expect'

import AdminPanel from './AdminPanel'

test('full app rendering/navigating',async () => {
  const history = createMemoryHistory()
  
  render(
    <Router history={history}>
      <AdminPanel />
    </Router>,
  )
  let title = await screen.findByText(/Admin Portal/i)
  expect(title).toBeInTheDocument()

}) 

检查你传递 props 的所有地方,看看是否有一些不相关的 prop 正在传递并且组件不需要。

在你附上的代码片段中,我只能看到 history 道具,检查出现错误的文件。

勾选Unknown Prop Warning:

The unknown-prop warning will fire if you attempt to render a DOM element with a prop that is not recognized by React as a legal DOM attribute/property. You should ensure that your DOM elements do not have spurious props floating around.

You are using a non-standard DOM attribute on a native DOM node, perhaps to represent custom data

例如

import React from 'react';
import { render, screen } from '@testing-library/react';
import '@testing-library/jest-dom/extend-expect';

const MenuItemGroup = (props) => <div {...props}>Admin Portal</div>;

export default function AdminPanel() {
  return (
    <div>
      <MenuItemGroup warnKey={1} className="menu-item-group" />
    </div>
  );
}

test('full app rendering/navigating', async () => {
  render(<AdminPanel />);
  expect(screen.findByText(/Admin Portal/i)).toBeInTheDocument();
});

warnKey不是标准的DOM属性,我们直接传给div元素,会触发上面的警告。解决方法是将我们自定义的非标准属性从props中解构出来,将classNameroleid等标准DOM属性通过展开运算符传递给目标元素.

更多标准HTML属性,可以查看All Supported HTML Attributes

const MenuItemGroup = ({ warnKey, ...rest }) => {
  // Use your custom props `warnKey`
  
  // `rest` props are all standard DOM attributes.
  return <div {...rest}>Admin Portal</div>;
}