javascript - 当组件更新 props 时点击 DOM 元素

标签 javascript reactjs click

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

最佳答案

我认为 componentWillReceivePropscomponentDidUpdate 都可以访问引用(虽然对第一个不是 100% 确定)。 componentWillReceiveProps 可以轻松检查 prop 是否实际更改,例如

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();
  }
}

另外,除非您确实依赖于 native 单击事件,否则直接调用单击处理程序通常会更干净,在您的情况下是 this.togglePlay。再说一次,我不知道这个函数的实现,所以也许你出于某种原因需要点击事件,但在大多数情况下它并不是真正必要的:)

关于javascript - 当组件更新 props 时点击 DOM 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47878595/

相关文章:

Javascript 继承 - 无法访问方法

javascript - 用主题 react 导航栏处理程序

javascript - 如何处理未接收 props 的 React 组件

audio - C#避免在按下KeyDown时发出哔哔声?

Javascript计算从多个选择中选择了多少个

javascript - Typeahead.js 下拉列表不出现

javascript - Firefox 的 monitorEvents() 等价物是什么?

reactjs - 如何防止父组件使用 React (next.js) SSR 两遍渲染重新渲染?

Java : ignore single click on double click?

javascript - 如何使用 Javascript/Jquery 单击标题属性等于特定变量的列表项?