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

React项目引入react-dnd时@DragDropContext装饰器报错求助

解决React DnD中@DragDropContext装饰器的Unexpected Token错误

我之前也踩过这个装饰器语法的坑,你已经装了相关插件但还是报错,大概率是配置没到位或者版本不匹配,给你梳理几个排查方向:

1. 检查Babel配置的插件顺序与格式

装饰器插件必须优先于其他类属性相关插件加载,否则会出现语法解析失败的问题。如果你用的是Babel 6(对应你安装的transform-decorators-legacy),确保你的.babelrc或babel.config.js是这样配置的:

{
  "presets": ["react", "es2015"],
  "plugins": [
    "transform-decorators-legacy",
    "transform-class-properties"
  ]
}

注意transform-decorators-legacy要放在transform-class-properties前面,顺序错了直接会导致Unexpected Token错误。

2. 确认React DnD版本是否适配

如果你的react-dnd是v14及以上的新版本,官方已经废弃了装饰器语法,转而推荐使用useDrag/useDrop Hooks写法。你可以先查看项目里的react-dnd版本,如果是新版本,建议直接改用更简洁的Hooks方式:

import { useDrag } from 'react-dnd';

function Card() {
  const [{ isDragging }, dragRef] = useDrag({
    type: 'CARD',
    item: { id: 'card-1' },
    collect: (monitor) => ({
      isDragging: monitor.isDragging(),
    }),
  });

  return <div ref={dragRef} style={{ opacity: isDragging ? 0.5 : 1 }}>拖动我</div>;
}

3. 如果你用的是Create React App(CRA)

CRA默认封装了Babel配置,直接安装Babel插件不会生效,必须通过以下方式处理:

  • 不可逆方案:运行npm run eject,然后在弹出的config/webpack.config.js中修改Babel配置,添加装饰器插件;
  • 推荐方案:用customize-cra和react-app-rewired覆盖配置,无需eject:
    1. 安装依赖:npm install customize-cra react-app-rewired --save-dev
    2. 在项目根目录创建config-overrides.js:
    const { override, addDecoratorsLegacy } = require('customize-cra');
    
    module.exports = override(
      addDecoratorsLegacy()
    );
    
    1. 修改package.json的启动脚本:
    "scripts": {
      "start": "react-app-rewired start",
      "build": "react-app-rewired build",
      "test": "react-app-rewired test"
    }
    

4. 检查Babel版本兼容性

你安装的transform-decorators-legacy只适配Babel 6,如果项目用的是Babel 7,需要换成新的插件:

  1. 卸载旧插件:npm uninstall babel-plugin-transform-decorators babel-plugin-transform-decorators-legacy
  2. 安装新插件:npm install @babel/plugin-proposal-decorators @babel/plugin-proposal-class-properties --save-dev
  3. 修改Babel配置:
{
  "presets": ["@babel/preset-react", "@babel/preset-env"],
  "plugins": [
    ["@babel/plugin-proposal-decorators", { "legacy": true }],
    ["@babel/plugin-proposal-class-properties", { "loose": true }]
  ]
}

建议先从Babel配置的顺序和正确性查起,这是最常见的触发原因。如果是CRA项目,一定要用rewire或eject的方式配置,直接修改.babelrc是无效的。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 08:35:59