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

Warning: Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()
原因是funtion组件(无状态组件)不能使用refs
解决,将函数组件通过用forwradRef包装
import React, { forwardRef } from 'react';const MyComponent = forwardRef((props, _ref) => {return <div> something here ......</div>}
https://blog.csdn.net/Jason847/article/details/106265566
connect连接redux后的组件,然后其他地方引用该组件后就提示以上警告,不影响使用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
import React, { forwardRef } from 'react';import PropTypes from 'prop-types';function App(props, ref) {return (<div ref={ref}/>)}const AppRef = forwardRef(App);AppRef.propTypes = {value: PropTypes.number.isRequired,onChange: PropTypes.func,};AppRef.defaultProps = {onChange: () => {},}export default AppRef;
错误的用法
forwardRef包裹 App后,再给 App设置 propTypes会报错
import React, { forwardRef } from 'react';import PropTypes from 'prop-types';App.propTypes = {value: PropTypes.number.isRequired,onChange: PropTypes.func,};App.defaultProps = {onChange: () => {},}function App() {}export default forwardRef(App);
forwardRef render functions accept exactly two parameters

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