背景
我试图使一个元素在动画结束后消失(我正在使用animate.css创建动画)。
以上“复制”文本在单击“复制到日志链接”时使用animated fadeOut
。此外,上面的演示显示,在链接上单击两次,就可以切换包含从显示到未显示的文本“复制”的跨度。
根据animate.css文档,还可以使用以下方法检测动画何时结束:
const element = document.querySelector('.my-element')
element.classList.add('animated', 'bounceOutLeft')
element.addEventListener('animationend', function() { doSomething() })
我的问题
然而,在componentDidMount()
tooltip
中,当试图集成animate.css文档时,null
就会出现。
我做错了什么?有更好的方法来处理这种行为吗?
ClipboardBtn.js
import React, { Component } from 'react'
import CopyToClipboard from 'react-copy-to-clipboard'
class ClipboardBtn extends Component {
constructor(props) {
super(props)
this.state = {
copied: false,
isShown: true,
}
}
componentDidMount() {
const tooltip = document.querySelector('#clipboard-tooltip')
tooltip.addEventListener('animationend', this.handleAnimationEnd)
}
handleAnimationEnd() {
this.setState({
isShown: false,
})
}
render() {
const { isShown, copied } = this.state
const { title, value } = this.props
return (
<span>
<CopyToClipboard onCopy={() => this.setState({ copied: !copied })} text={value}>
<span className="clipboard-btn">{title}</span>
</CopyToClipboard>
{this.state.copied ? (
<span
id="clipboard-tooltip"
className="animated fadeOut"
style={{
display: isShown ? 'inline' : 'none',
marginLeft: 15,
color: '#e0dbda',
}}
>
Copied!
</span>
) : null}
</span>
)
}
}
export default ClipboardBtn
发布于 2019-06-10 07:38:29
componentDidMount
在inital挂载期间只被调用一次。我可以看到,在inital组件状态下,copied
是false
,因此#clipboard-tooltip
永远不会被呈现。这就是工具提示为空的原因。
相反,试着这样做:
componentDidUpdate(prevProps, prevState) {
if(this.state.copied === true && prevState.copied === false) {
const tooltip = document.querySelector('#clipboard-tooltip')
tooltip.addEventListener('animationend', this.handleAnimationEnd)
}
if(this.state.copied === false && prevState.copied === true) {
const tooltip = document.querySelector('#clipboard-tooltip')
tooltip.removeEventListener('animationend', this.handleAnimationEnd)
}
}
每次componentDidUpdate
/状态更改都会被调用,因此,一旦copied
设置为true,事件处理程序就会在componentDidUpdate
中设置。我已经根据您的需求添加了一个条件,这样它就不会每次执行。随时根据需要进行调整。
发布于 2019-06-10 07:39:53
在React中使用查询选择器是一个很大的否定。你不应该这么做。(这不是问题所在)
但即使这不是问题,它也能解决你的问题:
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.myRef = React.createRef();
}
render() {
return <div ref={this.myRef} />;
}
}
https://stackoverflow.com/questions/56529369
复制相似问题