为什么我得到:在返回的组件实例上找不到 `render` 方法:您可能忘记定义 `render`

Why I am getting: No `render` method found on the returned component instance: you may have forgotten to define `render`

这是我得到的错误:

No `render` method found on the returned component instance: you may have forgotten to define `render`.
    in Component (at withScreenDimensionHOC.js:11)

HOC包装到class组件时出现的错误

export default connect(mapStateToProps, mapDispatchToProps)(
  withScreenDimensionHOC(ClassComponent)
);

这就是我创建自定义钩子和 HOC 的方式

我创建了自定义挂钩:

import { useEffect, useState } from 'react';

export const useScreenDimension = () => {
  const [width, setWidth] = useState(window.innerWidth);
  const [height, setHeight] = useState(window.innerHeight);

  useEffect(() => {
    const handleDimension = event => {
      setWidth(event.target.innerWidth);
      setHeight(event.target.innerHeight);
    };
    window.addEventListener('resize', handleDimension);
    return () => {
      window.removeEventListener('resize', handleDimension);
    };
  }, []);
  return { width, height };
};

HOC:

import React, { Component } from 'react';

import { useScreenDimension } from './useScreenDimension';

const withScreenDimensionHOC = () => {
  return props => {
    const { width, height } = useScreenDimension();
    return <Component width={width} height={height} {...props} />;
  };
};

withScreenDimensionHOC.displayName = 'withScreenDimensionHOC';

export default withScreenDimensionHOC;

然后将 HOC 包装到 class 组件


export default connect(mapStateToProps, mapDispatchToProps)(
  withScreenDimensionHOC(ClassComponent)
);

您正在尝试渲染 <Component>,React 的基础组件 class。

它没有渲染方法,就像错误所说的那样。您将一个组件传递给 withScreenDimensionHOC 但忽略它。不要忽视它 ;)

你的意思可能是这样的:

const withScreenDimensionHOC = WrappedComponent => (
  props => {
    const { width, height } = useScreenDimension()
    return <WrappedComponent width={width} height={height} {...props} />
  }
)