繁体   English   中英

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

[英]Add class to child component upon parent click

我有一个功能性的 React 组件,就像这样:

const RefreshButton = () => (

        <IconButton >
            <RefreshIcon />
        </IconButton>

)

What I need is to assign dynamically class attribute to child RefreshIcon node upon clicking IconButton ( onClick ), run CSS-animation bound to that class and remove that class as animation goes off ( onAnimationEnd ).

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

我遇到过这个话题,但它都是关于基于类的组件,我不确定如何采用建议的解决方案,所以如果你指出我正确的方向,我将不胜感激。

在反应中,大多数事情都是通过 state 更改来完成的。 当组件的 state(或 props)发生更改时,该组件将被重新渲染。 因此,在您的情况下,您需要根据一些 state 变量在元素上设置 class ,然后在您想从图标中添加/删除 class 时设置该变量。 这就是它的样子:

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

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

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

有很多方法可以解决这个问题。 我会使用参考并让 class 更改触发 animation。

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

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

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

暂无
暂无

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

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