与 JSS 反应 - 如何将 class 添加到 child 组件?

react with JSS - how to add class to child component?

我有一个包装器组件,它处理我的组件的安装和卸载动画,以及传递来自 parent 的任何其他道具。包装器将 classtoggleVisibility 道具添加到 child,这样我就可以将动画 css 添加到包含元素并从 [=37= 中改变可见性],但是我想将 css 应用于 child 的根元素,而不必更改 child 的代码来适应。这是我的代码:

<Animated visibility="initialOn" direction="down" >
  <Welcome testProp="Coool!" />
</Animated>

export const Animated = ({
  children,
  visible,
  direction = "up",
}: Props): JSX.Element => {
  const theme: any = useTheme();
  const [show, setShow] = useState(visible === "initialOn" || visible === true);
  if (visible !== "initialOn" && visible !== "initialOff") {
    if (show !== visible) {
      setShow(visible);
    }
  }
  const transitioned = useMountTransition(show, theme.defaultTransitionSpeed);
  const toggleVisibility = () => setShow(!show);
  const animatedClass = // this contains the JSS class I want to apply to the child's root element
    transitioned && show
      ? theme.animVisible[direction]
      : theme.animInVisible[direction];

  const childrenWithProps = React.Children.map(children, (child) => {
    if (React.isValidElement(child)) {
      return React.cloneElement(child, {
        toggleVisibility,
        animatedClass,
      });
    }
    return child;
  });

  return <>{(transitioned || show) && childrenWithProps}</>;
};

这是 child 组件,您可以看到我将附加样式注入 JSS 的位置。

export const useStyles = createUseStyles<any, any>((theme: any) => {
  const { modalOuter, animatedClass } = theme;
  return {
    splashOuter: { //container div
      ...modalOuter,
      marginLeft: "auto",
      marginRight: "auto",
      ...animatedClass, // apply animation styles
    },
  };
});

const Welcome = ({ toggleVisibility, animatedClass }: Props): JSX.Element => {
  const theme = { ...useTheme(), animatedClass }; // additional styles applied within here
  const styles = useStyles({ theme });
  return (
    <div className={styles.splashOuter}>
      <div className={styles.splashInner}>
        <button className={styles.button} onClick={toggleVisibility}>
          PROCEED
        </button>
      </div>
    </div>
  );
};

export default Welcome;

谢谢

解决方案比我预期的要简单得多。使用应用的样式将子组件包装在 div 中效果很好。谢谢

const childrenWithProps = React.Children.map(children, (child) => {
    if (React.isValidElement(child)) {
      return (
        <div className={styles.wrapper}>
          {React.cloneElement(child, {
            toggleVisibility,
          })}
        </div>
      );
    }
    return child;
  });