3

我刚刚升级到 React Bootstrap v. 0.27.1、React v. 0.14.0 和 React Router v. 1.0.0-rc3,现在当我使用某些 React Bootstrap 组件时,我遇到了Invariant Violation 。

未捕获的错误:不变违规:addComponentAsRefTo(...):只有 ReactOwner 可以有 refs。您可能正在向未在组件render方法中创建的组件添加 ref,或者您加载了多个 React 副本(详细信息:https ://fb.me/react-refs-must-have-owner )。

具体来说,我在使用<Input>and<Nav>组件时会看到这一点。所以我得到以下行为。

// Does NOT work.
// --------------
<Navbar>
    <Nav bsStyle="pills" activeKey={1}>
        <NavItem eventKey={1} href="/">Home</NavItem>
    </Nav>
</Navbar>

// Works
// -----
<Navbar>
    <ul className="nav nav-pills">
        <NavItem eventKey={1} href="/">Home</NavItem>
    </ul>
</Navbar>

如您所见,切换<Nav>到其常规 Bootstrap 标记可以解决问题。当我添加一个<Input>组件时也是如此。可能还有其他组件会导致故障,但我只将其范围缩小到这两个。

无论如何,我无法弄清楚为什么这些组件会发生这种情况而不是其他组件,任何帮助将不胜感激。

4

3 回答 3

1

我在 react-bootstrap 存储库中打开了这个问题,有人指出这不是 React Bootstrap 特定的,而是因为加载了两个 React 副本而引起的。似乎是 Browserify 导致了这个问题,因为我能够通过在我的构建过程中添加browserify-resolutions来解决这个问题。由于我使用 Gulp,我的 gulpfile 最终包含以下两个任务。请注意,browserify-resolutions 是使用该.plugin(resolutions, 'react')行调用的。

// Compile third-party dependencies separately for faster performance.
gulp.task('browserify-vendor', function() {
    return browserify()
        .require(dependencies)
        .plugin(resolutions, 'react')
        .bundle()
        .pipe(source('vendor.bundle.js'))
        .pipe(gulpif(production, streamify(uglify({ mangle: false }))))
        .pipe(gulp.dest('public/js'));
});

// Compile only project files, excluding all third-party dependencies.
gulp.task('browserify', ['browserify-vendor'], function() {
    return browserify('src/app.js')
        .external(dependencies)
        .plugin(resolutions, 'react')
        .transform(babelify)
        .bundle()
        .pipe(source('bundle.js'))
        .pipe(gulpif(production, streamify(uglify({ mangle: false }))))
        .pipe(gulp.dest('public/js'));
});
于 2015-10-12T09:57:47.117 回答
0

如果出于任何原因您来到这里寻找解决方案并且没有任何工作。并且如果您还使用 create-react-app ,那么我建议您检查 index.html 文件中的多个“构建”捆绑包,这些捆绑包react正在加载多个或任何导致Invariant Violation错误的东西。希望它可以帮助某人。

于 2018-05-30T11:48:47.913 回答
0

感谢张贴胡安。我确实尝试过 browserify-resolutions,但它完全拒绝对捆绑包中的两个 React 副本进行重复数据删除。最后,我通过删除整个 node_modules 文件夹并重新安装完整的 npm 来解决问题。

这具有删除 React 0.14.0 包含在 react-dom 下的依赖项的效果(这导致了构建时的重复)。我想知道这是否可能归结为使用扁平文件夹结构的最新 NPM,该文件夹结构会自动在层次结构中进行重复数据删除。

在此之后,我没有任何问题,并且根本不需要使用 browserify-resolutions。

于 2015-10-13T12:08:32.717 回答