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 />
在该州,您可以更有效地存储 currentTarget
, clientX
等并在 render()
上生成 react 元素循环。来自archived react docs
What shouldn't go in the state? - React components: Build them in render() based on underlying props and state data.
react material-ui library 有一个循环 Material 波纹,如果你需要一些例子来说明在实践中是如何做到的,你可以看看它。 Here is the source对于他们的波纹组件,您可以通过单击一些 buttons on this page 来查看演示.
要点是它们只允许固定数量的波纹元素,并使用 ReactTransitionGroup
处理启动和中止动画。每次添加涟漪时,都会删除涟漪数组的第一个元素并添加一个新项目。
但是,如果您不关心这些 - 您可以通过在调用 removeRipple
时从数组中删除第一个波纹来修复代码。 .由于您总是将最新的波纹添加到数组的末尾,因此第一个总是最旧的。
removeRipple = (e) => {
// create a new element with the first element removed
const [, ...shiftedRipples] = this.state.ripples;
// update the state
this.setState({ ripples: shiftedRipples });
}
关于javascript - 从 React 的事件处理程序中删除动态 DOM 节点的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47385701/