React组件事件处理程序无法找到this。

3

我一直在对一些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,我的this就完全没有作用域了。我以为可能是错误的(比如window或其他什么),但看起来是未定义的。
Uncaught TypeError: Cannot read property 'top' of undefined

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


你能分享一下你的 package.json 和打包配置,例如 webpack.config.js 吗?我发现每当出现这个错误时,都意味着我有两份 React 的副本被加载了,原因可能是什么。 - Sam Ternent
1个回答

0
我们通过简单地引用事件对象和目标来解决了这个问题。它可以达到相同的结果(获取DOM节点并用jQuery包装),但感觉上不太符合“React的方式”。话虽如此,animate()方法也不是“React的方式”,但为了遵循规范而进一步复杂化事情并没有必要。
handleMove(e) {
    let $arrow = $(ReactDOM.findDOMNode(e.target));

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接