繁体   English   中英

Styled-jsx 样式不适用于 Framer-Motion 元素

[英]Styled-jsx styling not applied to Framer-Motion element

我想我正在失去理智。

我创建了一个新的 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>
    </>
  )
}

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

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

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}
        </>
    )
}

我发现这个css.resolve事后申请非常麻烦。
这是另一种大部分时间都有效的方法。 需要注意的是,它将应用于具有相同.test class 的所有子组件。 (只需在必要时添加另一个父级)

import {motion} from 'framer-motion';

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM