You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React高阶组件(HOC)无法调用传入组件,报错求助

高阶组件(HOC)传递组件报错排查与解决

问题场景

我编写了名为SectionWrapper的高阶组件,代码如下:

import React from 'react'
import { motion } from 'framer-motion'
import { styles } from '../styles'
import { staggerContainer } from '../utils/motion'
const SectionWrapper = ({Component, idName}) => function HOC(){
        return (
            <motion.section
            variants={staggerContainer()}
            initial='hidden'
            whileInView='show'
            viewport={{once: true, amount:0.25}}
            className={`${styles.padding} max-w-7xl mx-auto relative z-0`}
            >
                <Component/>
            </motion.section>
        )
}

export default SectionWrapper

在About.jsx中使用该HOC包裹About组件并导出:

export default SectionWrapper(About, 'about')

运行时触发错误:

react-dom.development.js:28439 Uncaught Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.

Check the render method of `HOC`.

删除HOC中的<Component/>后代码可正常运行,怀疑组件传递方式有问题,但参考视频中相同代码能正常运行,需要排查解决方法。

核心问题

你的HOC定义时用了对象解构参数({Component, idName}),但调用时却传递了两个独立参数(About和'about'),导致Component参数始终是undefined,渲染时自然触发错误。

修复方案

两种方法任选其一:

方法1:修改HOC的参数接收逻辑

把HOC改成直接接收两个独立参数,而非解构对象:

import React from 'react'
import { motion } from 'framer-motion'
import { styles } from '../styles'
import { staggerContainer } from '../utils/motion'
// 直接接收Component和idName作为独立参数
const SectionWrapper = (Component, idName) => function HOC(){
        return (
            <motion.section
            variants={staggerContainer()}
            initial='hidden'
            whileInView='show'
            viewport={{once: true, amount:0.25}}
            className={`${styles.padding} max-w-7xl mx-auto relative z-0`}
            id={idName} // 可以把idName用在section上,实现传入id的作用
            >
                <Component/>
            </motion.section>
        )
}

export default SectionWrapper

修改后原调用方式SectionWrapper(About, 'about')即可正常工作。

方法2:修改HOC的调用方式

保持HOC代码不变,调用时传递包含Component和idName的对象:

// About.jsx中修改导出语句
export default SectionWrapper({ Component: About, idName: 'about' })

额外检查项

  • 确认About组件本身已正确导出:比如组件文件中是否有export default About,如果是命名导出,导入时要对应使用import { About } from './xxx'。
  • 检查staggerContainer、styles等依赖是否正确导出和导入,避免其他潜在的undefined问题。

内容的提问来源于stack exchange,提问作者Mihailo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 14:35:31