Мне труднее всего заставить это работать. Я перешел от обработчика асинхронных событий к текущей функции. В настоящее время происходит то, что происходит, если вы выбираете элемент, который является последним в родительском div, он в конечном итоге имеет тот же zIndex, а другой элемент все еще размещается сверху.
Я в основном пытаюсь убедиться, что мой оператор if гарантирует, что элемент, который я нажимаю, имеет самый высокий zIndex. Это весь код моего компонента, основная функция, на которую нужно обратить внимание, - это onStart. Я оставляю все в беспорядке в надежде, что кто-то сможет понять, чего я пытаюсь достичь, и помочь мне:
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)
this.state = {
highestIndex: 0
}
}
findHighestZIndex(elem) {
let elems = document.getElementsByClassName(elem);
let highest = 0;
for (let i = 0; i < elems.length; i++) {
let zindex =document.defaultView.getComputedStyle(elems[i],null)
.getPropertyValue("z-index");
if ((zindex > highest) && (zindex != 'auto')) {
this.setState({
highestIndex: zindex
})
}
}
}
onStart(e) {
this.findHighestZIndex("react-draggable")
if (this.state.highestIndex >= 0) {
console.info('greater than zero', this.state.highestIndex, e.currentTarget.style.zIndex)
e.currentTarget.style.zIndex = (+this.state.highestIndex) + (+1)
this.setState({
highestIndex: (+e.currentTarget.style.zIndex) + 1
})
} else if (this.state.highestIndex < e.currentTarget.style.zIndex) {
console.info('lower')
e.currentTarget.style.zIndex = (+this.state.highestIndex) + (+2)
} else {
console.info('catch')
}
// if (this.state.highestIndex >= 0) {
// this.setState({
// highestIndex: (+this.state.highestIndex) + 1
// })
// e.currentTarget.style.zIndex = (+this.state.highestIndex) + 1
// console.info(e.currentTarget.style.zIndex)
// }
}
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



![Безумие обратных вызовов в javascript [JS]](https://i.imgur.com/WsjO6zJb.png)


Похоже, вы всегда устанавливаете this.state.highestIndex и zIndex текущей цели одинаковыми в первом операторе if (). Поэтому когда выполняется инструкция else if (), она всегда ложна.
См. Закомментированный код ниже.
if (this.state.highestIndex >= 0) { // This is always going to be true!!
console.info('greater than zero', this.state.highestIndex, e.currentTarget.style.zIndex)
e.currentTarget.style.zIndex = (+this.state.highestIndex) + (+1)// Now you're setting the zIndex of the current target to higher than this.state.highestIndex
this.setState({
highestIndex: (+e.currentTarget.style.zIndex) + 1 // And now setting highestIndex to be identical to current target's zIndex.
})
} else if (this.state.highestIndex < e.currentTarget.style.zIndex) { // Now this will never be true because you set them equal in the first if block.
console.info('lower')
e.currentTarget.style.zIndex = (+this.state.highestIndex) + (+2)
} else {
console.info('catch')
}
Вы, наверное, хотите что-то вроде этого (непроверено)
if (this.state.highestIndex >= 0) { // This is always going to be true!!
e.currentTarget.style.zIndex = this.state.highestIndex + 2 // Add 2
this.setState({
highestIndex: this.state.highestIndex++; // Increment highestIndex by 1.
}) // Now current target has a zIndex 1 higher than the rest
} else {
console.info('catch')
}
Но на самом деле это тоже потенциально плохое решение, потому что в конечном итоге zIndex может достичь максимума и, следовательно, больше не будет работать. Было бы лучше просто установить для всех элементов zIndex значение 1, а затем установить для текущей цели более высокое значение. Сбрасывая их каждый раз. Возможно, что-то в этом роде (удаление вашей функции, чтобы найти наивысший zIndex и вызовы setState).
onStart(e) {
let elems = document.getElementsByClassName('react-draggable');
for(let i = 0; i < elems.length; i++) {
elems[i].style.zIndex = 1;
e.currentTarget.style.zIndex = 2;
}
}
Ваш путь намного лучше, ха-ха. Я обдумал ситуацию. Спасибо!