【问题标题】:Problems with ChakraUI Custom Menu ButtonChakraUI 自定义菜单按钮的问题
【发布时间】:2022-07-13 20:43:52
【问题描述】:

我正在使用 ChakraUI 为我的网站创建菜单。我想将我的自定义图像组件设置为来自 ChakraUI 的菜单组件正常工作所需的 MenuButton。我尝试了两种在网上找到的方法,这些是我遇到的问题:

方法一:forwardRefs

正如网站所说,我编写了代码,以便我的自定义组件可以接受 MenuButton 传递的引用。遗憾的是按钮不起作用。

const Menu = () => {
  const { user, signOut } = useAuth();

  return (
    <motion.div
      initial={{
        opacity: 0,
      }}
      animate={{ opacity: 1 }}
      transition={{ duration: 0.4, delay: 0.2 }}
    >
      <Menu>
        <MenuButton as={CustomButton}></MenuButton>
        <MenuList>
          <MenuItem>Test</MenuItem>
        </MenuList>
      </Menu>
    </motion.div>
  );
};
import { forwardRef } from "@chakra-ui/react";

const CustomButton= forwardRef((props, ref) => {
  const { user, signOut } = useAuth();

  return (
    <motion.img
      ref={ref}
      whileHover={{ scale: 1.1, rotate: "-360deg" }}
      whileTap={{
        scale: 0.95,
        borderRadius: "10rem",
      }}
      src={
        "https://source.boringavatars.com/beam/240/" + user.email + "?square"
      }
      height="50px"
      width="50px"
    />
  );
});

方法二:Chakra Framer Motion

按照网站说的做了。该按钮现在可以正常工作,但是一旦我单击该按钮,动画就会无限期地停止工作。

import { motion } from 'framer-motion'

const ProfileButton = () => {
  const { user, signOut } = useAuth();
  const MotionMenuButton= motion(MenuButton)

  return (
    <motion.div
      initial={{
        opacity: 0,
      }}
      animate={{ opacity: 1 }}
      transition={{ duration: 0.4, delay: 0.2 }}
    >
      <Menu>
        <MotionMenuButton
           whileHover={{ scale: 1.1, rotate: "-360deg" }}
           whileTap={{
             scale: 0.95
      }}>
           <Image
             src={"https://source.boringavatars.com/beam/240/" + user.email + "?square"}/>
        </MotionMenuButton>
        <MenuList>
          <MenuItem>Bonk</MenuItem>
        </MenuList>
      </Menu>
    </motion.div>
  );
};

我哪里错了?

【问题讨论】:

    标签: reactjs chakra-ui


    【解决方案1】:

    我知道这是一个老问题,但可能会对遇到同样问题的人有所帮助。

    在方法1中,确保也传播props对象:

    import { forwardRef } from "@chakra-ui/react";
    
    const CustomButton= forwardRef((props, ref) => {
      const { user, signOut } = useAuth();
    
      return (
        <motion.img
          ref={ref}
          whileHover={{ scale: 1.1, rotate: "-360deg" }}
          whileTap={{
            scale: 0.95,
            borderRadius: "10rem",
          }}
          src={
            "https://source.boringavatars.com/beam/240/" + user.email + "?square"
          }
          height="50px"
          width="50px"
          props={...props}
        />
      );
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-02-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-16
      • 2014-09-02
      • 2012-07-22
      相关资源
      最近更新 更多