我有一个组件,它在 componentDidMount
生命周期方法上有一个单击事件。
我需要每次触发组件渲染时单击 div。
我的问题是 componentDidMount
仅触发一次,并且当组件重新渲染时,不会触发单击事件。
我没有找到任何其他可以使用单击事件的生命周期方法。
是否可以通过其他方式实现?
点击方法:
componentDidMount() {
this.setState({
audioPlayer: ReactDOM.findDOMNode(this.refs.audio)
}, () => {
this.state.audioPlayer.ontimeupdate = () => { this.timeUpdated() };
this.state.audioPlayer.onprogress = () => { this.progressUpdated() };
if(this.props.playing) {
this.divElement.click();
}
});
}
引用的div:
<div className='player__control__icons--play'>
<div ref={div => this.divElement = div} className='player__control__icon' onClick={this.togglePlay.bind(this)}>
<Play />
</div>
{skipButtons}
</div>
最佳答案
我认为 componentWillReceiveProps
和 componentDidUpdate
都可以访问引用(虽然对第一个不是 100% 确定)。 componentWillReceiveProps
可以轻松检查 prop 是否实际更改,例如
componentWillReceiveProps (nextProps) {
if (!this.props.playing && nextProps.playing) {
this.divElement.click();
}
}
另外,除非您确实依赖于 native 单击事件,否则直接调用单击处理程序通常会更干净,在您的情况下是 this.togglePlay
。再说一次,我不知道这个函数的实现,所以也许你出于某种原因需要点击事件,但在大多数情况下它并不是真正必要的:)
关于javascript - 当组件更新 props 时点击 DOM 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47878595/