如何将成帧器运动与材质ui一起使用?(reactjs)(@material-ui/core)(帧器运动)



我只想知道是否有一种方法可以将成帧器运动材质Ui一起使用。我试过了,但没有成功。

Material-UI为这类需求提供了component道具选项,应该比包装方法做得更好、更优雅。然后,您可以将framer-motion包提供的任何道具传递给Material-UI组件,只要它们不冲突(我不确定是否有(。

<Button
color="inherit"
variant='contained'
size="large"
component={motion.div}
whileHover={{
scale: 1.2,
transition: { duration: 0.3 }
}}
whileTap={{ scale: 0.9 }}
>
Button
</Button>

你的问题让我很好奇。我从未尝试过框架运动,但最近正计划学习它。

所以我尝试了一下,创建了一个沙盒,在里面添加了一个Material UI和framer动作包

只是使用MaterialUI在页面中间创建了一个小按钮。并使用<motion.div>标签包装按钮,如下所示:

import React from "react";
import { motion } from "framer-motion";
import Button from "@material-ui/core/Button";
function AnimatableDiv() {
return (
<motion.div
className="animatable"
whileHover={{
scale: 1.2,
transition: { duration: 0.3 }
}}
whileTap={{ scale: 0.9 }}
>
<Button size="large" className="animatable">
Button
</Button>
</motion.div>
);
}
export default AnimatableDiv;

它成功了

您可能在想,如果我直接在<Button>组件上使用motion.,如下图所示:

<motion.Button size="large" className="animatable">
Button
</motion.Button>

嗯,我确实想到了这一点,我也应用了它,Material UI应用于该按钮的所有样式都丢失了所以不要采用这种方法!我再说一遍,不要

下面的链接可以查看:https://codesandbox.io/s/brave-sutherland-5bki9

我也遇到了同样的情况,所以经过一次小规模的研究和一些尝试和错误,我写了一篇关于这方面的小文章,希望你们能从中得到帮助,如果有任何建议可以在评论部分详细阐述。

https://aishmn.medium.com/how-to-use-material-ui-and-framer-motion-together-6026fed96a4c

接受答案的策略是实现这一点的最简单方法,但另一种策略是使用framer motion的包装。

这是我用Typescript为那些可能搜索这个问题的人实现的。

Box.tsx

import React from "react";
import { motion } from "framer-motion";
import MuiBox, { BoxProps } from "@mui/material/Box";
const BoxComponent = React.forwardRef((props: BoxProps, ref) => (
<MuiBox {...props} ref={ref} />
));
const Box = motion(BoxComponent);
export default Box;

然后在组件中使用它

import Box from "./Box";
// The motion-wrapped Mui Box now also accepts framer-motion's props
<Box
initial={{ opacity: 0 }}
animate={{ x: 100, rotate: [null, 10, 20], opacity: 1 }}
whileHover={{ scale: [null, 1.5, 1.4] }}
width={100}
height={100}
border="1px solid red"
/>

我也有同样的问题,所以我在运动文档中挖掘了一点。我发现:通过使用motion((函数包装任何组件,都可以将其转换为运动组件。所以我做了这个:

import { TextField } from "@mui/material";
import { motion } from "framer-motion";
export default function YourComponent() {
const TextFieldMotion = motion(TextField);
return (
<TextFieldMotion 
animate={{ x: [0,20] }} 
transition = {{ ease: "easeInOut", duration: 3 }} 
variant="filled" 
label="first name" 
/>
)
};

有关详细信息:https://www.framer.com/docs/component/

最新更新