DOM操作是JS库提供的最简单的功能。但在React中,所有动态的东西都必须在状态中。这使得仅添加或删除简单的DOM节点变得非常困难。也许这是React的缺点,或者我可能不知道其他方法。
看一下这个例子--
看一下这个例子--
class Ripple extends React.Component {
state = {
ripples: []
}
render() {
const { className } = this.props;
return (
<div onClick={this.rippleNow} className={`${className} material__ripple`}>
{this.props.children}
{this.state.ripples.map((Item, index) => (
<Item key={index} />
))}
</div>
);
}
rippleNow = ({ currentTarget, clientX, clientY }) => {
const { x, y } = currentTarget.getBoundingClientRect(),
{ offsetHeight, offsetWidth } = currentTarget,
dia = Math.min(offsetHeight, offsetWidth, 100);
const styles = {
top: (clientX - x) - dia / 2,
left: (clientY - y) - dia / 2,
width: dia,
height: dia
}
const Wave = () => (
<div onAnimationEnd={this.removeRipple} style={styles}></div>
);
this.setState(prev => {
ripples: [...prev.ripples, Wave]
});
}
removeRipple = (e) => {
// How will i remove that element?
// Or is there any other way to do the same?
}
}
我该如何从状态中移除元素?或者在React中是否有其他添加或删除DOM元素的方法。由于React不允许直接修改DOM,所以我陷入了困境。
我真的很需要帮助,感谢那些愿意尝试帮助我的人。
Wave
组件将被添加,并且我正在尝试在其动画结束时删除每个元素。 - Ruhul AminisAnimationEnded
,然后在渲染时,进行!isAnimationEnded && someOtherChecks ? <Component {...props}/> : null
的操作。 - Rajesh