react runtime_error ai_generated true

警告:forwardRef 渲染函数只接受两个参数:props 和 ref。你是否意外地将 children 作为单独的参数传递了?

Warning: forwardRef render functions accept exactly two parameters: props and ref. Did you accidentally pass children as a separate prop?

ID: react/forwardref-children-prop

其他格式: JSON · Markdown 中文 · English
90%修复率
85%置信度
1证据数
2023-03-15首次发现

版本兼容性

版本状态引入弃用备注
React 16.8+ active
React 17.x active
React 18.x active

根因分析

使用 React.forwardRef 时,渲染函数签名是 (props, ref) => JSX。将 children 作为第三个参数传递或错误解构 ref 会导致此警告,常见于包装一个期望 children 作为 prop 的组件时。

English

When using React.forwardRef, the render function signature is (props, ref) => JSX. Passing children as a third argument or destructuring ref incorrectly causes this warning, often when wrapping a component that expects children as a prop.

generic

官方文档

https://reactjs.org/docs/forwarding-refs.html

解决方案

  1. Ensure the forwardRef callback has exactly two parameters: props and ref. Access children via props.children. Example: const MyComponent = React.forwardRef((props, ref) => <div ref={ref}>{props.children}</div>);
  2. If using TypeScript, define the component with React.PropsWithChildren<P> and forwardRef: const MyComponent = React.forwardRef<HTMLDivElement, React.PropsWithChildren<{}>>((props, ref) => ...);
  3. For class components, avoid forwardRef and use a callback ref pattern: <div ref={(node) => { this.myRef = node; }}>

无效尝试

常见但无效的做法:

  1. 95% 失败

    React's forwardRef only passes two arguments; the third parameter is always undefined.

  2. 85% 失败

    React does not pass ref through props; it's a separate argument. This breaks ref forwarding.

  3. 70% 失败

    Overcomplicates the component hierarchy without fixing the forwardRef signature mismatch.