【问题标题】:React component event handler can't find thisReact 组件事件处理程序找不到这个
【发布时间】:2016-03-10 00:27:44
【问题描述】:

我一直在对一些 React 组件进行一些(据说)轻微的重构工作。由于某种原因,其中一个已按预期停止工作——网上提出的其他问题类似,但似乎不足以解决我的情况。

我有这个组件,有条件地从父级渲染:

'use strict';

import React from 'react';
import ReactDOM from 'react-dom';

class ArrowButton extends React.Component {

    handleMove() {
        let $arrow = $(ReactDOM.findDOMNode(this));
        let $banner = $arrow.parents('.hero-banner');
        let bannerBottom = $banner.offset().top + $banner.outerHeight();

        $('html, body').animate({
            scrollTop: bannerBottom
        });
    }

    render() {
        return (
            <div className="arrow-button" onClick={this.handleMove.bind(this)}>
                <div className="arrow-button__arrow"></div>
            </div>
        );
    }
}

export default ArrowButton;

它的父级将它放置在自身内部,如下所示:

displayArrowButton() {
    if (this.props.showArrow) {
        return <ArrowButton />;
    }
}
...
{this.displayArrowButton()}

问题:单击带有绑定事件处理程序的按钮(与其他地方一样)会导致一个奇怪的错误,我不禁认为这是一个红鲱鱼:

Warning: React can't find the root component node for data-reactid value `.0.2.0.0.1`. If you're seeing this message, it probably means that you've loaded two copies of React on the page. At this time, only a single copy of React can be loaded at a time.
Uncaught TypeError: Cannot read property 'firstChild' of undefined

如果我删除 .bind,我根本没有这个余地。我认为它可能是错误的(如在窗口或其他东西中)但似乎未定义。

Uncaught TypeError: Cannot read property 'top' of undefined

我找不到任何奇怪的参考,其中我们两次包含了 React。我应该仔细检查(不)常见的问题吗?为什么具有相同设置的其他组件(处理程序主体除外)可以工作?

【问题讨论】:

  • 你能分享你的package.json和捆绑配置,例如webpack.config.js吗?我发现每当出现该错误时 - 这确实意味着我出于某种原因加载了 2 个 react 副本。

标签: javascript reactjs


【解决方案1】:

我们通过简单地引用事件对象和目标来解决这个问题。它实现了相同的结果(到达 DOM 节点并用 jQuery 包装它),但感觉不太“React 方式”。话虽这么说,animate() 方法也没有,但也没有必要无缘无故地让事情变得更复杂。

handleMove(e) {
    let $arrow = $(ReactDOM.findDOMNode(e.target));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-01-25
    • 2013-11-02
    • 1970-01-01
    • 1970-01-01
    • 2017-09-21
    • 2016-10-31
    • 2022-08-09
    • 1970-01-01
    相关资源
    最近更新 更多