React中的事件处理程序在Promise中返回null

时间:2018-08-07 00:39:01

标签: javascript reactjs

我有2个功能。第一个函数返回一个Promise,该Promise在页面上找到最高的zIndex。第二个函数处理onClick。因此,当我按下一个元素时,它会循环通过某些div,找到最大的zIndex,然后加1。

这是代码:

  findHighestZIndex(elem) {
    return new Promise((res, err) => {
      if(!elem) console.log(err)

      let highest = Array.from(document.getElementsByClassName(elem))
      .map(a => parseInt(window.getComputedStyle(a).zIndex), 100)
      .filter(a => !isNaN(a))
      .sort()
      .pop();

      return res(highest);
    })
  }

  onStart(e) {

    let frame = e.currentTarget

    this.findHighestZIndex('react-draggable').then((res) => {

      if(res >= 0) {
        frame.style.zIndex = (+res) + 2
        console.log(e.currentTarget)
      } else {
        frame.style.zIndex = 1
      }

    }).catch((err) => {
      console.log('error')
    })

  }

e.currentTarget返回null。如果我将currentTarget存储在变量中,则它将起作用,直到您两次单击同一元素为止。

有更好的方法吗?

这是我的整个组件:

import React, {Component} from 'react'
import Draggable from 'react-draggable'
import Router from 'next/router'


import {
  BrowserFrame, 
  DragHandle,
  BrowserContent 
} from './styles'

class DesktopBrowser extends Component {

  constructor(props) {
    super(props)
  }

  findHighestZIndex(elem) {
    return new Promise((res, err) => {
      if(!elem) console.log(err)

      let highest = Array.from(document.getElementsByClassName(elem))
      .map(a => parseInt(window.getComputedStyle(a).zIndex), 100)
      .filter(a => !isNaN(a))
      .sort()
      .pop();

      return res(highest);
    })
  }

  onStart(e) {

    let frame = e.currentTarget

    this.findHighestZIndex('react-draggable').then((res) => {

      if(res >= 0) {
        frame.style.zIndex = (+res) + 2
        console.log(e.currentTarget)
      } else {
        frame.style.zIndex = 1
      }

    }).catch((err) => {
      console.log('error')
    })

  }




  render() {
   return (
      <Draggable 
        bounds="body"
        handle=".drag-handle"
        onStart={this.onStart.bind(this)}
        defaultPosition={
          {
            x: Math.floor(Math.random() * Math.floor(document.getElementsByClassName('content')[0].offsetWidth - 1000)), 
            y: Math.floor(Math.random() * Math.floor(document.getElementsByClassName('content')[0].offsetHeight - 500)) 
          }
        }>
      <BrowserFrame>
        <DragHandle className="drag-handle" />
        <BrowserContent bg={this.props.content.image}>
          <button onClick={(e) => {
            e.preventDefault()
            Router.push(`/portfolio/${this.props.content.slug}`)
          }}>View</button>
        </BrowserContent>

      </BrowserFrame>
      </Draggable>
    )
  }
}

export default DesktopBrowser

0 个答案:

没有答案