加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

reactjs – React中事件处理程序的奇怪行为

发布时间:2020-12-15 20:12:12 所属栏目:百科 来源:网络整理
导读:我想知道是否有人可以解释这种行为的原因: 如果来自 input的onChange事件我设置的元素指向这个方法: private PasswordChanged = (event: any) = { this.setState((prevState: IWifiState,props: IWifiProps) = { prevState.Password = event.target.value;
我想知道是否有人可以解释这种行为的原因:

如果来自< input>的onChange事件我设置的元素指向这个方法:

private PasswordChanged = (event: any) => {
    this.setState((prevState: IWifiState,props: IWifiProps) => {
        prevState.Password = event.target.value;
        return prevState;
    });
}

这让我有以下错误:

Error

其中第27行恰好是对粘贴代码的event.target.value的调用.

如果我改为代码那样:

private PasswordChanged = (event: any) => {
    const password = event.target.value;
    this.setState((prevState: IWifiState,props: IWifiProps) => {
        prevState.Password = password;
        return prevState;
    });
}

它只是按预期工作……任何人都可以解释为什么?

谢谢!

解决方法

React做了一个名为 Event Pooling的事情.

这实质上意味着,出于性能考虑,它们会重复使用事件.

在您调用setState时,内部对象可能无法重新使用,因为它可能以您不希望的方式运行(一旦事件服务于其目的,属性就会被取消).

最好将变量中的引用保存为所需的值,并将其用作代码.

基本上,您是异步访问它(在setState函数内),建议不要这样做.

有一个解决方法,但我也建议反对它.

If you want to access the event properties in an asynchronous way,you should call event.persist() on the event,which will remove the synthetic event from the pool and allow references to the event to be retained by user code.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读