onTouchTap 使用 material-ui 对话框触发两次

IT技术 reactjs material-ui
2021-05-14 18:49:21

我们已经构建了一个使用 Material-ui 来显示对话框的 React 项目。出于某种原因,当您单击触发对话框打开的按钮时,似乎会触发第二个触摸事件,这可能会触发对话框上的链接或按钮。当您通过单击按钮关闭对话框时会发生类似的问题。执行此操作时,对话框将关闭,但会在您单击的元素正后方的元素上触发另一个触摸事件。

react-tap-event-plugin为了使用 Material-ui,我们已经包含了,并且只要在这种幽灵点击行为上没有 2 个元素重叠,该应用程序就可以很好地工作。

这是我们组件的简化版本:

import React, { Component } from 'react'
import Dialog from 'material-ui/Dialog'

class Introduction extends Component {
  constructor(props) {
    super(props)

    this.state = { complete: false }

    this.finish = this.finish.bind(this)
  }

  finish() {
    this.setState({ complete: true })
  }

  render() {
    const actions = (
      <div>
        <button onTouchTap={this.finish}>Finish</button>
      </div>
    )

    if (!this.state.complete) {
      return (
        <Dialog open actions={actions}>
          <h3>Dialog header</h3>
          <p>Dialog text</p>
        </Dialog>
      )
    }

    return null
  }
}

当单击“完成”操作按钮时,对话框关闭,然后它后面的元素也会收到 touchTap 事件。

如果它有所作为,我们将使用 Cordova 来包装移动应用程序。我们仅在移动设备上(肯定在 iOS 上)遇到此问题,在 Chrome 中测试时也在设备模式下遇到此问题。

我究竟做错了什么?任何意见,将不胜感激。

2个回答

问题在于,无论您是否处理 onTouchTap 事件,都会在延迟后触发 onClick 事件。因此,在触发 onTouchTap 事件并且您的 Dialog 关闭后,在触发 onTouchTap 事件的同一位置延迟后会出现另一个 onClick 事件。因此,对话框消失后,位于“触摸”“下方”的任何元素都将收到 onClick 事件。

要解决此问题:在 onTouchTap 事件处理程序中调用 e.preventDefault()。像这样:

<Button onTouchTap={(e) => { e.preventDefault(); this.finish()}}>Finish</Button>

希望这可以帮助。

当我运行您的代码时,出现此错误:

Uncaught TypeError: Cannot read property 'setState' of null

所以 this 关键字为空。您需要将函数绑定到类实例。在构造函数中使用:

constructor(props) {
  super(props)
  this.finish = this.finish.bind(this);
  this.state = { complete: false }
}

或者

<button onTouchTap={this.finish.bind(this}>Finish</button>

或者您可以使用自动绑定到类的 es6 箭头函数。

finish = () => {
  this.setState({ complete: true })
}

我想当您尝试使用按钮打开它时会出现同样的问题。