首页 > 解决方案 > Styled-jsx 样式不适用于 Framer-Motion 元素

问题描述

我想我正在失去理智。

我创建了一个新的 Nextjs 项目,通过 NPM 安装 Framer-Motion,以开发模式运行该项目。一切都会编译并加载页面,但是一旦我向元素添加动作,它就会消失而没有错误。

我在PC和Mac上都得到了这个。我什至删除了我的节点模块和 package.lock 文件,并回滚到我过去工作过的 Next.js 和 framer-motion 版本,但它没有成功。只是为了好玩,我用 framer-motion 创建了一个新的 react 应用程序,它在那里没有问题。

import {motion} from 'framer-motion';

export default function Home() {
  return (
    <>
      <motion.div
        className="test"
        animate={{ scale: 1.5 }}
      />
      <style jsx>{`
        .test {
          width: 100px;
          height: 100px;
          background-color: red;
        }
      `}</style>
    </>
  )
}

标签: reactjsnext.jsframer-motionstyled-jsx

解决方案


那是因为您的styled-jsx样式未应用于framer-motion元素。

要设置第三方组件的样式,例如motion.div元素,您需要使用resolve来自styled-jsx/css.

import { motion } from 'framer-motion';
import css from 'styled-jsx/css';

const { className, styles } = css.resolve`
  div {
    width: 100px;
    height: 100px;
    background: red;
  }
`;

export default function Home() {
    return (
        <>
            <motion.div
                className={className}
                animate={{ scale: 1.5 }}
            />
            {styles}
        </>
    )
}

推荐阅读