在父级单击时将类添加到子组件

时间:2019-11-15 14:28:39

标签: javascript reactjs

我有一个功能强大的React组件,像这样:

const RefreshButton = () => (

        <IconButton >
            <RefreshIcon />
        </IconButton>

)

我需要的是在单击RefreshIconIconButton)后为子onClick节点动态分配类属性,运行绑定到该类的CSS动画,并在动画进行时删除该类关闭(onAnimationEnd

我的问题是,我完全不知道如何从onClickonAnimationEnd回调中引用子组件。

我遇到过that主题,但这全都是基于类的组件,我不确定如何采用建议的解决方案,因此,如果您指出正确的方向,我将不胜感激。

3 个答案:

答案 0 :(得分:3)

大多数情况下,通过状态更改来完成操作。当组件的状态(或道具)更改时,将重新渲染该组件。因此,在您的情况下,您需要基于某个状态变量在元素上设置类,然后在您想要从图标添加/删除类时设置该变量。如下所示:

const RefreshButton = () => {
    const [iconClass, setIconClass] = React.useState("");

    const onButtonClick = () => {
        setIconClass("animation-class");
    }

    <IconButton onClick={onButtonClick}>
        <RefreshIcon className={iconClass}/>
    </IconButton>
}

答案 1 :(得分:2)

有很多方法可以解决此问题。我将使用ref's并让类更改触发动画。

import React, { useRef } from 'react'

const RefreshButton = () => {
  const buttonInput = useRef(null);

  const onButtonClick = () => {
    // Do animations based on class change
    buttonInput.classList.add()
  };

  return (
    <IconButton onClick={onButtonClick} >
      <RefreshIcon ref={buttonInput} />
    </IconButton>
  )
}

答案 2 :(得分:0)

如果您的组件不是动态组件,并且您可以控制它,则可以使其与类相关的道具一起使用。可能看起来像这样:

const RefreshIcon = (props) => {
    const className = `my-class-name ${props.className}`;
    return (
        <div className={className}>...</div>
    )
}

,然后在您的父组件中:

const RefreshButton = () => (
    [isAnimaionOn, setIsAnimationOn] = useState(false);

    <IconButton>
        <RefreshIcon className={isAnimaionOn ? "animation-on-class" : "animation-off-class"} />
    </IconButton>
)