嗨,我正在尝试使用自定义钩子来制作可拖动组件,但我遇到了这个问题 “ TypeError:无法读取null的属性'style'”
这是自定义钩子的代码
elems = driver.find_elements_by_xpath("//div[@class='g-recaptcha']")
val = elem.get_attribute("data-sitekey")
print val.text
这里是组件
import { useState } from "react";
const useDragable = dragItem => {
const [active, setActive] = useState(false);
const [currentX, setCurrentX] = useState(0);
const [currentY, setCurrentY] = useState(0);
const [initialX, setInitialX] = useState(0);
const [initialY, setInitialY] = useState(0);
const [xOffset, setXoffset] = useState(0);
const [yOffset, setYoffset] = useState(0);
const dragStart = e => {
console.log("dragItem");
console.log(dragItem);
e.target.classList.add("dragging");
setInitialX(e.clientX - xOffset);
setInitialY(e.clientY - yOffset);
setActive(true);
};
const dragEnd = e => {
e.target.classList.remove("dragging");
setInitialX(currentX);
setInitialY(currentY);
setActive(false);
};
const drag = e => {
if (active) {
e.preventDefault();
setCurrentX(e.clientX - initialX);
setCurrentY(e.clientY - initialY);
setXoffset(currentX);
setYoffset(currentY);
}
setTranslate(currentX, currentY, dragItem.current);
};
function setTranslate(xPos, yPos, el) {
if (el) {
el.style.transform = "translate3d(" + xPos + "px, " + yPos + "px, 0)";
}
}
return [dragStart, dragEnd, drag];
};
export default useDragable;
React引发无限渲染错误
答案 0 :(得分:0)
不确定100%,但是
if (el) {
// your code
}
这可以防止错误,但我认为不会解决
答案 1 :(得分:-1)
我找到了问题!
使用useRef时,您不必在前面加上“ this”。
这就是为什么它会产生错误的原因,第二次尝试更改时,我将其放在“ ref = {dragIm}”中