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

如何将含三种引号的代码转为字符串存入数据库?遇motion未定义错误

问题描述

我需要将代码存入数据库,为避免代码中的引号与包裹代码的引号冲突,尝试用String()包裹JSX代码,结果触发ReferenceError,提示motion未定义——哪怕这段代码已经在String()内部。

尝试的代码

const snippits = [
    {
        title: "random 01",
        code: String(
            <div>
                <motion.p 
                    className='text-text bg-primary-button absolute px-4 py-2 rounded-lg shadow-lg z-10'
                    animate={{ y: [null, '0.5rem', '0rem'] }}
                    transition={{ delay: 3, times: [0, 0.2, 1] }}
                >
                    CTRL + C
                </motion.p>
                <p className='text-black bg-black/50 relative px-4 py-2 rounded-lg shadow-lg top-2'>CTRL + C</p>
            </div>
        ),
        tags: ["hello", "world"],
        votes: 15,
        favorite: true
    }
]

报错信息

- error ReferenceError: motion is not defined
    at Home (./src/app/page.jsx:19:97)
    at stringify (<anonymous>)
digest: "2300908980"
   8 |             code: String(
   9 |                 <div>
> 10 |                     <motion.p
     |                     ^
  11 |                         className='text-text bg-primary-button absolute px-4 py-2 rounded-lg shadow-lg z-10'
解决方案

问题根源

你可能误以为String()会直接把JSX转成字符串,但实际上JSX在编译阶段会被转换成框架的元素创建函数(比如React的React.createElement)调用。哪怕用String()包裹,JSX仍然会先被解析执行,motion.p会被当作组件去查找,找不到motion变量自然就报错了——这和String()没有任何关系。

正确实现方式

要把JSX作为字符串存储,不能直接写JSX语法,而是用模板字符串直接编写HTML/JSX的文本内容:

const snippits = [
    {
        title: "random 01",
        code: `
            <div>
                <motion.p 
                    className='text-text bg-primary-button absolute px-4 py-2 rounded-lg shadow-lg z-10'
                    animate={{ y: [null, '0.5rem', '0rem'] }}
                    transition={{ delay: 3, times: [0, 0.2, 1] }}
                >
                    CTRL + C
                </motion.p>
                <p className='text-black bg-black/50 relative px-4 py-2 rounded-lg shadow-lg top-2'>CTRL + C</p>
            </div>
        `,
        tags: ["hello", "world"],
        votes: 15,
        favorite: true
    }
]

额外提示

  1. 如果代码中需要使用反引号(`),用转义符\处理即可,比如写成```
  2. 存入数据库时,优先使用参数化查询(如SQL的预编译语句),这是避免引号冲突最安全的方案,比手动处理字符串可靠得多
  3. 后续渲染这段字符串时,React中可以用dangerouslySetInnerHTML,但务必注意XSS安全风险;其他框架也要遵循对应的安全渲染规范

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 08:57:09