1. 出现 ts 构建报错,起因是 @types/react 发布了 18 放弃了一些声明兼容, 而项目里面没有直接依赖 @types/react 版本的关系。
  2. 解决方法,通过 tnpm i @types/react@16 --save-dev 来解决。
  3. Warning: Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?
  4. App.propTypes = {
  5. onChange: func,
  6. className: string,
  7. };
  8. Warning: forwardRef render functions do not support propTypes or defaultProps. Did you accidentally pass a React component?
  9. Warning: forwardRef render functions accept exactly two parameters: props and ref. Did you forget to use the ref parameter?
  10. 原因:forwardRef会让stateless 无状态组件的defaultPropspropTypes属性失效。
  11. https://github.com/facebook/react/issues/16653
  12. https://stackoverflow.com/questions/59716140/using-forwardref-with-proptypes-and-eslint
  13. https://juejin.cn/post/6844904165492129799

Function components cannot be given refs

image.png
Warning: Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()
原因是funtion组件(无状态组件)不能使用refs
解决,将函数组件通过用forwradRef包装

  1. import React, { forwardRef } from 'react';
  2. const MyComponent = forwardRef((props, _ref) => {
  3. return <div> something here ......</div>
  4. }

https://blog.csdn.net/Jason847/article/details/106265566

  1. connect连接redux后的组件,然后其他地方引用该组件后就提示以上警告,不影响使用
  2. export default connect(stateToProps, null, null, { forwardRef: true })(SelectEnumNode);

defaultProps

Warning: forwardRef render functions do not support propTypes or defaultProps. Did you accidentally pass a React component
参考 https://github.com/facebook/react/issues/16653

用 forwardRef包裹函数组件报错,
原因:forwardRef会让 stateless无状态函数组件的 defaultProps和propTypes属性失效

正确的设置 propTypes

  1. import React, { forwardRef } from 'react';
  2. import PropTypes from 'prop-types';
  3. function App(props, ref) {
  4. return (
  5. <div ref={ref}/>
  6. )
  7. }
  8. const AppRef = forwardRef(App);
  9. AppRef.propTypes = {
  10. value: PropTypes.number.isRequired,
  11. onChange: PropTypes.func,
  12. };
  13. AppRef.defaultProps = {
  14. onChange: () => {},
  15. }
  16. export default AppRef;

错误的用法
forwardRef包裹 App后,再给 App设置 propTypes会报错

  1. import React, { forwardRef } from 'react';
  2. import PropTypes from 'prop-types';
  3. App.propTypes = {
  4. value: PropTypes.number.isRequired,
  5. onChange: PropTypes.func,
  6. };
  7. App.defaultProps = {
  8. onChange: () => {},
  9. }
  10. function App() {}
  11. export default forwardRef(App);

forwardRef render functions accept exactly two parameters

image.png
forwardRef的2个参数 props, ref
Warning: forwardRef render functions accept exactly two parameters: props and ref. Did you forget to use the ref parameter?