【问题标题】:click DOM element when component updates props组件更新 props 时单击 DOM 元素
【发布时间】:2017-12-19 10:24:09
【问题描述】:

我有一个组件在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>

【问题讨论】:

标签: javascript reactjs click


【解决方案1】:

我认为componentWillReceivePropscomponentDidUpdate 都可以访问参考文献(虽然不是 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。再说一次,我不知道这个函数的实现,所以也许你出于某种原因需要点击事件,但在大多数情况下它并不是真的必要:)

【讨论】:

  • 谢谢!您的评论真的帮我解决了问题!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-10-30
  • 2023-04-03
  • 2016-02-21
  • 1970-01-01
  • 2021-07-13
  • 1970-01-01
  • 2012-07-15
相关资源
最近更新 更多