gpt4 book ai didi

javascript - ReactJS 无法使用 event.persist() 设置事件的状态

转载 作者:行者123 更新时间:2023-12-03 12:57:31 24 4
gpt4 key购买 nike

我需要设置一个从事件中获取的状态字段,但当我将函数传递给它时它不会被设置。组件和方法如下所示:

constructor(props: SomeProps, context: any) {
super(props, context);
this.state = {
isFiltering: props.isFiltering,
anchor: "",
};
}

private toggleFilter = (event: any) => {
event.persist()
this.setState(prevState => ({
isFiltering: !prevState.isFiltering,
anchor: event.currentTarget // does not work, it's null
}));
}

如果我删除 event.persist() 则会收到以下错误:

This synthetic event is reused for performance reasons. If you're seeing this, you're accessing the method currentTarget on a released/nullified synthetic event. This is a no-op function. If you must keep the original synthetic event around, use event.persist(). See https://facebook.github.io/react/docs/events.html#event-pooling for more information.

出于某种原因,以下代码有效:

private toggleFilter = (event: any) => {
this.setState({anchor:event.currentTarget}) // works fine
this.setState(prevState => ({
isFiltering: !prevState.isFiltering,
}));
}

为什么上面的方法有效,但当我使用 this.setState(prevState=> ...) 时却无效?

最佳答案

这是预期的行为,因为 event.persist() 并不意味着 currentTarget 没有被取消,事实上它应该be - 与浏览器的 native 实现兼容。

这意味着,如果您想以异步方式访问 currentTarget,则需要将其缓存在变量中,就像您在答案中所做的那样。

<小时/>

引用 React 核心开发人员之一 - Sophie Alpert .

currentTarget changes as the event bubbles up – if you had a event handler on the element receiving the event and others on its ancestors, they'd see different values for currentTarget. IIRC nulling it out is consistent with what happens on native events; if not, let me know and we'll reconsider our behavior here.

查看the source官方 React 存储库中的讨论以及 Sophie 提供的以下片段是我接触过的。

var savedEvent;
var savedTarget;

divb.addEventListener('click', function(e) {
savedEvent = e;
savedTarget = e.currentTarget;
setTimeout(function() {
console.log('b: currentTarget is now ' + e.currentTarget);
}, 0);
}, false);

diva.addEventListener('click', function(e) {
console.log('same event object? ' + (e === savedEvent));
console.log('same target? ' + (savedTarget === e.currentTarget));
setTimeout(function() {
console.log('a: currentTarget is now ' + e.currentTarget);
}, 0);
}, false);
div {
padding: 50px;
background: rgba(0,0,0,0.5);
color: white;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body>

<div id="diva"><div id="divb"> Click me and see output! </div></div>

</body>
</html>

关于javascript - ReactJS 无法使用 event.persist() 设置事件的状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42089795/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com