ReactJS componentDidMount 的行为与 Bootstrap 不符合预期

ReactJS componentDidMount does not behave as expected with Bootstrap

我想在呈现的 DOM 上调用 $(dom).popover()。所以我有:

module.exports = React.createClass({
    componentDidMount: function() {
        $(this.getDOMNode()).popover();
    },
    render: function() {
        return ( // My DOM );
    }
})

此 returns 错误:TypeError: $(...).popover is not a function。但是,如果我在 componentDidMount 中延迟,那么它会起作用,即:

componentDidMount: function() {
    var _this = this;
    setTimeout(function () {
        $(_this.getDOMNode()).popover();
    }, 250);
}

如何在不使用 setTimeout 的情况下完成同样的事情?

确保你已经像这样正确地包含了你的 js 文件:

<html>
    <body>
        ...

        <script src="jquery.js"></script>
        <script src="bootstrap.js"></script>

        <!-- Your js file that starts React app -->
        <script src="myapp.js"></script>
    </body>
</html>

尝试将您的 jquery 代码放入 $(document).ready().

:

componentDidMount: function() {
var _this = this;
$(document).ready(function() {
    $(_this.getDOMNode()).popover();
});
}

编辑 #1:回应评论:"You should also explain why" – Rohit Gupta

问为什么太多,会毁了这一切的美好。

开玩笑。我遇到了答案,因为我遇到了与 OP 相同的问题。我在 componentDidMount 函数中使用 jQuery 重新初始化 Materialize.css 手风琴小部件(使用 jQuery)——或者至少我在尝试。但它并没有像我想象的那样工作。

然后我来到这里,看到OP尝试使用setTImeout,并且成功了;我尝试过这个;它对我有用——即使是在 1 毫秒——然后我想到在文档(就绪)函数中拍打可能会起作用,因为基本上它做的事情类似于 componentDidMount 生命周期函数。 $(document).ready 在回调中运行任何内容之前侦听整个文档加载 --compondentDidMount 在运行任何内容之前侦听要安装的组件。

当你在 componentDidMount 函数中放置一个 $(document).ready 函数(并将所有通常只在后者中的东西放入前者​​)时,它会延迟 componentDidMount 函数中的代码直到加载整个文档,而不仅仅是 componentDidMount 函数所在的组件。popover 函数作用于页面中尚未加载的某些元素。使用OP的原始代码可以在页面加载完成后在控制台手动调用popover事件,然后初始化效果,这意味着popover所需的元素在调用componentDidMount时不存在,但确实存在页面完全加载后——这就是 $(document).ready 起作用的原因:那是它的回调被触发的时候。

这至少是我的理论 :) 关于它为何起作用的任何替代理论?

如果您在代码中定义了导入文字,请尝试删除。

// import * as $ from "jquery";