我有一个组件,在componentDidMount
生命周期方法上有一个click事件。
每次组件的渲染触发时,我都需要单击div。
我的问题是componentDidMount
只触发一次,当重新渲染组件时,不会触发click事件。
我没有找到任何其他生命周期方法,其中click事件将起作用。
是否有可能以任何其他方式做到这一点?
点击方法:
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
都可以访问refs(不是100%肯定第一个)。 componentWillReceiveProps
可以很容易地检查道具是否实际发生了变化,例如:
componentWillReceiveProps (nextProps) {
if (!this.props.playing && nextProps.playing) {
this.divElement.click();
}
}
另外作为旁注,除非你真的依赖本机点击事件,否则直接调用点击处理程序通常更简洁,在你的情况下this.togglePlay
。同样,我不知道这个函数的实现,所以也许你出于某种原因需要click事件,但在大多数情况下它并不是真的必要:)