组件更新道具时单击DOM元素

问题描述 投票:1回答:1

我有一个组件,在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>
javascript reactjs click
1个回答
0
投票

我认为componentWillReceivePropscomponentDidUpdate都可以访问refs(不是100%肯定第一个)。 componentWillReceiveProps可以很容易地检查道具是否实际发生了变化,例如:

https://developmentarc.gitbooks.io/react-indepth/content/life_cycle/update/component_will_receive_props.html

componentWillReceiveProps (nextProps) {
  if (!this.props.playing && nextProps.playing) {
    this.divElement.click();
  }
}

另外作为旁注,除非你真的依赖本机点击事件,否则直接调用点击处理程序通常更简洁,在你的情况下this.togglePlay。同样,我不知道这个函数的实现,所以也许你出于某种原因需要click事件,但在大多数情况下它并不是真的必要:)

© www.soinside.com 2019 - 2024. All rights reserved.