- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试使用 React hooks 创建这个旋转 div
示例的副本。 https://codesandbox.io/s/XDjY28XoV
这是我到目前为止的代码
import React, { useState, useEffect, useCallback } from 'react';
const App = () => {
const [box, setBox] = useState(null);
const [isActive, setIsActive] = useState(false);
const [angle, setAngle] = useState(0);
const [startAngle, setStartAngle] = useState(0);
const [currentAngle, setCurrentAngle] = useState(0);
const [boxCenterPoint, setBoxCenterPoint] = useState({});
const setBoxCallback = useCallback(node => {
if (node !== null) {
setBox(node)
}
}, [])
// to avoid unwanted behaviour, deselect all text
const deselectAll = () => {
if (document.selection) {
document.selection.empty();
} else if (window.getSelection) {
window.getSelection().removeAllRanges();
}
}
// method to get the positionof the pointer event relative to the center of the box
const getPositionFromCenter = e => {
const fromBoxCenter = {
x: e.clientX - boxCenterPoint.x,
y: -(e.clientY - boxCenterPoint.y)
};
return fromBoxCenter;
}
const mouseDownHandler = e => {
e.stopPropagation();
const fromBoxCenter = getPositionFromCenter(e);
const newStartAngle =
90 - Math.atan2(fromBoxCenter.y, fromBoxCenter.x) * (180 / Math.PI);
setStartAngle(newStartAngle);
setIsActive(true);
}
const mouseUpHandler = e => {
deselectAll();
e.stopPropagation();
if (isActive) {
const newCurrentAngle = currentAngle + (angle - startAngle);
setIsActive(false);
setCurrentAngle(newCurrentAngle);
}
}
const mouseMoveHandler = e => {
if (isActive) {
const fromBoxCenter = getPositionFromCenter(e);
const newAngle =
90 - Math.atan2(fromBoxCenter.y, fromBoxCenter.x) * (180 / Math.PI);
box.style.transform =
"rotate(" +
(currentAngle + (newAngle - (startAngle ? startAngle : 0))) +
"deg)";
setAngle(newAngle)
}
}
useEffect(() => {
if (box) {
const boxPosition = box.getBoundingClientRect();
// get the current center point
const boxCenterX = boxPosition.left + boxPosition.width / 2;
const boxCenterY = boxPosition.top + boxPosition.height / 2;
// update the state
setBoxCenterPoint({ x: boxCenterX, y: boxCenterY });
}
// in case the event ends outside the box
window.onmouseup = mouseUpHandler;
window.onmousemove = mouseMoveHandler;
}, [ box ])
return (
<div className="box-container">
<div
className="box"
onMouseDown={mouseDownHandler}
onMouseUp={mouseUpHandler}
ref={setBoxCallback}
>
Rotate
</div>
</div>
);
}
export default App;
当前,即使状态实际上为 true,mouseMoveHandler 也会以 isActive = false
的状态调用。我怎样才能让这个事件处理程序以正确的状态触发?
此外,控制台正在记录警告:
React Hook useEffect has missing dependencies: 'mouseMoveHandler' and 'mouseUpHandler'. Either include them or remove the dependency array react-hooks/exhaustive-deps
为什么我必须在 useEffect 依赖数组中包含组件方法?我从未需要使用 React Hooks 对其他更简单的组件执行此操作。
谢谢
最佳答案
Why is
isActive
false?
const mouseMoveHandler = e => {
if(isActive) {
// ...
}
};
(为了方便起见,我只讨论 mouseMoveHandler
,但这里的所有内容也适用于 mouseUpHandler
)
当上面的代码运行时,会创建一个函数实例,该实例会拉入 isActive
变量通过 function closure 。该变量是一个常量,因此如果 isActive
当函数定义时为 false,那么它总是将是 false
只要该函数实例存在。
useEffect
还需要一个函数,并且该函数有一个对您的 moveMouseHandler
的常量引用函数实例 - 只要 useEffect 回调存在,它就会引用 moveMouseHandler
的副本哪里isActive
是假的。
何时 isActive
更改、组件重新渲染以及 moveMouseHandler
的新实例将在其中创建 isActive
是 true
。然而,useEffect
仅当依赖项发生更改时才重新运行其函数 - 在本例中,依赖项 ( [box]
) 未更改,因此 useEffect
不重新运行且版本为moveMouseHandler
哪里isActive
为 false 时仍附加到窗口,无论当前状态如何。
这就是为什么“exhaustive-deps”钩子(Hook)警告您 useEffect
- 它的一些依赖项可以更改,而不会导致 Hook 重新运行并更新这些依赖项。
由于钩子(Hook)间接依赖于 isActive
,您可以通过添加 isActive
来解决此问题到deps
useEffect
的数组:
// Works, but not the best solution
useEffect(() => {
//...
}, [box, isActive])
但是,这不是很干净:如果您更改 mouseMoveHandler
所以它取决于更多的状态,你会遇到同样的错误,除非你记得把它添加到 deps
数组也是如此。 (linter 也不会喜欢这样)
useEffect
函数间接依赖于isActive
因为它直接取决于mouseMoveHandler
;因此,您可以将其添加到依赖项中:
useEffect(() => {
//...
}, [box, mouseMoveHandler])
通过此更改,useEffect 将使用新版本的 mouseMoveHandler
重新运行。这意味着它将尊重 isActive
。 但是它会运行得太频繁 - 它每次都会运行 mouseMoveHandler
成为一个新的函数实例...这是每个渲染,因为每个渲染都会创建一个新函数。
我们并不需要每次渲染都创建一个新函数,只有当isActive
时才需要创建一个新函数。已更改:React 提供了 useCallback
该用例的钩子(Hook)。您可以定义您的mouseMoveHandler
如
const mouseMoveHandler = useCallback(e => {
if(isActive) {
// ...
}
}, [isActive])
现在只有在 isActive
时才会创建新的函数实例更改,然后将触发 useEffect
在适当的时刻运行,您可以更改 mouseMoveHandler
的定义(例如添加更多状态)而不破坏您的 useEffect
钩子(Hook)。
这可能仍然会给您的 useEffect
带来问题hook:每次都会重新运行isActive
变化,这意味着它每次都会设置框中心点 isActive
更改,这可能是不需要的。您应该将效果分成两个单独的效果以避免此问题:
useEffect(() => {
// update box center
}, [box])
useEffect(() => {
// expose window methods
}, [mouseMoveHandler, mouseUpHandler]);
<小时/>
最终您的代码应如下所示:
const mouseMoveHandler = useCallback(e => {
/* ... */
}, [isActive]);
const mouseUpHandler = useCallback(e => {
/* ... */
}, [isActive]);
useEffect(() => {
/* update box center */
}, [box]);
useEffect(() => {
/* expose callback methods */
}, [mouseUpHandler, mouseMoveHandler])
Dan Abramov,React 作者之一,在他的 Complete Guide to useEffect 中详细介绍了更多细节。博文。
关于reactjs - 使用 React Hooks,为什么我的事件处理程序会以错误的状态触发?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55874789/
我正在尝试将 WPF CodeBehid 事件(如 Event、Handler、EventSetter)转换为 MVVM 模式。我不允许使用 System.Windows.Controls,因为我使用
我可能误解了 Backbone 中的事件系统,但是当我尝试以下代码时什么也没有发生。当我向 Backbone.Events 扩展对象添加新属性时,它不应该触发某种更改、更新或重置事件吗?就像模型一样吗
我遇到了一个简单的问题,就是无法弄清楚为什么它不起作用。我有一个子组件“app-buttons”,其中我有一个输入字段,我想听,所以我可以根据输入值过滤列表。 如果我将输入放在我有列表的根组件中,一切
System.Timers.Timer 的 Elapsed 事件实际上与 System.Windows.Forms.Timer 的 Tick 事件相同吗? 在特定情况下使用其中一种比使用另一种有优势吗
嗨,这个 javascript 代码段是什么意思。(evt) 部分是如此令人困惑.. evt 不是 bool 值。这个怎么运作? function checkIt(evt) { evt
我正在使用jquery full calendar我试图在事件被删除时保存它。 $('calendar').fullCalendar ({
我有两个链接的鼠标事件: $('body > form').on("mousedown", function(e){ //Do stuff }).on("mouseup", function(
这是我的代码: $( '#Example' ).on( "keypress", function( keyEvent ) { if ( keyEvent.which != 44 ) {
我尝试了 dragOver 事件处理程序,但它没有正常工作。 我正在研究钢琴,我希望能够弹奏音符,即使那个键上没有发生鼠标按下。 是否有事件处理程序? 下面是我正在制作的钢琴的图片。 最佳答案 您应该
当悬停在相邻文本上时,我需要使隐藏按钮可见。这是通过 onMouseEnter 和 onMouseLeave 事件完成的。但是当点击另外的文本时,我需要使按钮完全可见并停止 onMouseLeave
我有ul标签内 div标签。我申请了mouseup事件 div标记和 click事件 ul标签。 问题 每当我点击 ul标签,然后都是 mouseup和 click事件被触发。 我想要的是当我点击 u
我是 Javascript 和 jQuery 的新手,所以我有一个非常愚蠢的疑问,请耐心等待 $(document).click(function () { alert("!"); v
我有一个邮政编码解析器,我正在使用 keyup 事件处理程序来跟踪输入长度何时达到 5,然后查询服务器以解析邮政编码。但是我想防止脚本被不必要地调用,所以我想知道是否有一种方法可以跟踪 keydown
使用事件 API,我有以下代码来发布带有事件照片的事件 $facebook = new Facebook(array( "appId" => "XXX", "se
首次加载 Microsoft Word 时,既不会触发 NewDocument 事件也不会触发 DocumentOpen 事件。当 Word 实例已打开并打开新文档或现有文档时,这些事件会正常触发。
我发现了很多相关问题(这里和其他地方),但还没有具体找到这个问题。 我正在尝试监听箭头键 (37-40) 的按键事件,但是当以特定顺序使用箭头键时,后续箭头不会生成“按键”事件。 例子: http:/
给定的 HTML: 和 JavaScript 的: var $test = $('#test'); $test.on('keydown', function(event) { if (eve
我是 Node.js 的新手,希望使用流运行程序。对于其他程序,我必须同时启动一个服务器(mongodb、redis 等),但我不知道我是否应该用这个运行一个服务器。请让我知道我哪里出了问题以及如何纠
我正在尝试使用 Swift 和 Cocoa 创建一个适用于 OS X 的应用程序。我希望应用程序能够响应关键事件,而不将焦点放在文本字段上/文本字段中。我在 Xcode 中创建了一个带有 Storyb
我有以下代码: (function(w,d,s,l,i){ w[l]=w[l]||[];w[l].push({
我是一名优秀的程序员,十分优秀!