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

使用React Transition Group的CSSTransition组件报错,求解决方案

问题排查与解决

1. 修复组件JSX返回语法

你的Application组件未用return包裹JSX内容,这是语法错误。即使移除CSSTransition能运行,大概率是你实际代码里有return但粘贴时遗漏了,补上后再测试:

function Application () {
  const [modalIsOpen, setModalOpen] = React.useState(false);

  const openModal = () => {
    setModalOpen(true);
  };

  const closeModal = () => {
    setModalOpen(false);
  };

  // 必须添加return包裹JSX
  return (
    <div className="wrap">
      <CSSTransition
        in={modalIsOpen}
        timeout={500}
        classNames="modal-overlay"
      >
        <div>
          <Modal
            title="Modal Title"
            onClose={closeModal}
            content={<p>Hello world</p>}
          />
        </div>
      </CSSTransition>
    </div>
  );
}

2. 替换React片段为具体容器元素

CSSTransition要求子元素是单个可渲染的元素/组件,React片段(<>)在部分版本的react-transition-group中无法被正确识别,会触发组件类型无效的错误。把片段替换成<div>或其他容器元素即可。

3. 确认依赖安装与版本兼容性

  • 确保已正确安装依赖:
    npm install react-transition-group
    # 或
    yarn add react-transition-group
    
  • 若使用React 18,建议安装react-transition-group v4.x或v5.x版本,避免版本不匹配导致的导入问题。

4. 验证导入语句正确性

CSSTransition是命名导出,必须用大括号包裹导入,拼写错误或误用默认导入会导致获取到undefined:

// 正确写法
import { CSSTransition } from 'react-transition-group';

// 错误写法(会导致问题)
import CSSTransition from 'react-transition-group';

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 06:05:27