【发布时间】:2020-03-27 21:35:27
【问题描述】:
我创建了一个脚本,该脚本在鼠标悬停在父容器上时激活,并且应该将其子元素从鼠标移开。我目前已经让它工作了,但是代码的某些部分似乎与 REACT 代码的外观相矛盾。尤其是两个部分。
-
我在渲染函数中使用了一个计数器,以便每个 span 从
state.customProperties获取正确的自定义属性,state.customProperties是一个在父元素鼠标悬停时更新自定义属性的数组。render() { let counter = 0; const returnCustomProp = function(that) { counter++; let x = 0; if (that.state.customProperties[counter - 1]) { x = that.state.customProperties[counter - 1].x; } let y = 0; if (that.state.customProperties[counter - 1]) { y = that.state.customProperties[counter - 1].y; } return "customProperty(" + x + " " + y + ")"; } return ( <div onMouseMove={this._testFunction} id="ParentContainer"> <section custom={returnCustomProp(this)}> <b>Custom content for part 1</b> <i>Could be way different from all the other elements</i> </section> <section custom={returnCustomProp(this)}> 2 </section> <section custom={returnCustomProp(this)}> <div> All content can differ internally so I'm unable to create a generic element and loop trough that </div> </section> <section custom={returnCustomProp(this)}> 4 </section> <section custom={returnCustomProp(this)}> 5 </section> <section custom={returnCustomProp(this)}> <div> <b> This is just test data, the actualy data has no divs nested inside secions </b> <h1> 6 </h1> </div> </section> <section custom={returnCustomProp(this)}> 7 </section> <section custom={returnCustomProp(this)}> 8 </section> </div> ); } -
在 mousemove 函数中,我使用
document.getElementById和querySelectorAll来获取所有部分元素并将鼠标坐标与部分元素坐标进行比较。var mouseX = e.pageX; var mouseY = e.pageY; var spans = document.getElementById('ParentContainer').querySelectorAll('section'); var theRangeSquared = 10 * 10; var maxOffset = 5; var newCustomProperties = []; for (var i = 0; i < spans.length; i++) { var position = spans[i].getBoundingClientRect(); var widthMod = position.width / 2; var heightMod = position.height / 2; var coordX = position.x + widthMod; var coordY = position.y + heightMod + window.scrollY; // Distance from mouse var dx = coordX - mouseX; var dy = coordY - mouseY; var distanceSquared = (dx * dx + dy * dy); var tx = 0, ty = 0; if (distanceSquared < theRangeSquared && distanceSquared !== 0) { // Calculate shift scale (inverse of distance) var shift = maxOffset * (theRangeSquared - distanceSquared) / theRangeSquared; var distance = Math.sqrt(distanceSquared); tx = shift * dx / distance; ty = shift * dy / distance; } newCustomProperties.push({ x: tx, y: ty }); }
我有一种感觉,这一切都错了。我不确定如何在保持通用 returnCustomProp 函数返回所述元素的属性的同时避免计数器(在实时代码中,我有大约 200 个这些元素,因此手动为它们设置数组项号是效率不高)。
第二部分感觉很难通过 ID 来定位实际组件内部的元素。我觉得我应该能够在不遍历 DOM 的情况下定位它。引用部分元素可能是一种解决方案,但我认为应该将引用保持在最低限度,并且如上所述,实际代码由数百个这些部分组成。
除了更新custom="customProperty(0 0)" 属性之外,代码并没有做更多的atm。您可以通过鼠标悬停时的元素检查器看到这种情况。
我能否在不必计算渲染函数中的<section> 元素且不必使用document.querySelectorAll 的情况下使此功能正常工作?
【问题讨论】: