[英]Add class to child component upon parent click
I have a functional React component, like that:我有一个功能性的 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
). 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
).
My problem is that I have absolutely no clue as of how do I refer child Component from within onClick
and onAnimationEnd
callbacks.我的问题是我完全不知道如何从onClick
和onAnimationEnd
回调中引用子组件。
I have come across that topic, but it's all about class-based components and I'm not really sure how to adopt proposed solution, so I'd appreciate a lot if you point me to the right direction.我遇到过这个话题,但它都是关于基于类的组件,我不确定如何采用建议的解决方案,所以如果你指出我正确的方向,我将不胜感激。
In react most things are done through state changes.在反应中,大多数事情都是通过 state 更改来完成的。 When the state (or props) of a component changes the component will be re-rendered.当组件的 state(或 props)发生更改时,该组件将被重新渲染。 So in your case you'll want to set the class on the element based on some state variable and then set that variable when you want to add/remove the class from the icon.因此,在您的情况下,您需要根据一些 state 变量在元素上设置 class ,然后在您想从图标中添加/删除 class 时设置该变量。 Here's what that would look like:这就是它的样子:
const RefreshButton = () => {
const [iconClass, setIconClass] = React.useState("");
const onButtonClick = () => {
setIconClass("animation-class");
}
<IconButton onClick={onButtonClick}>
<RefreshIcon className={iconClass}/>
</IconButton>
}
There are lots of ways to solve this.有很多方法可以解决这个问题。 I'd use ref's and let the class change trigger the animation.我会使用参考并让 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>
)
}
If your component is not a dynamic component and you have control of it then you can make it work with class related prop.如果您的组件不是动态组件并且您可以控制它,那么您可以使其与 class 相关的道具一起使用。 That might look something like that:这可能看起来像这样:
const RefreshIcon = (props) => {
const className = `my-class-name ${props.className}`;
return (
<div className={className}>...</div>
)
}
and then in your parent component:然后在您的父组件中:
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.