首页 > 解决方案 > 将 JQuery 放在 React 组件中的什么位置?

问题描述

我在我的 React 应用程序中使用物化 css 库。所以,我想从中使用“模态”。有两种初始化方法:

document.addEventListener('DOMContentLoaded', function() {
var elems = document.querySelectorAll('.modal');
var instances = M.Modal.init(elems, options);
 });

// Or with jQuery

$(document).ready(function(){
$('.modal').modal();
});

所以,我通常这样做第二种方式:

componentDidMount() {
    const $ = window.$;
    $('.dropdown-trigger').dropdown();
    $(document).ready(function () {
        $('.modal').modal();
    })
}

这一切都对我有用,但现在我的 ComponentDidMount() 中有一个额外的方法,它请求服务器 api:

componentDidMount() {
    this.getCurrentUser();
    const $ = window.$;
    $('.dropdown-trigger').dropdown();
    $(document).ready(function () {
        $('.modal').modal();
    })
}

getCurrentUser() {
    fetch('api/user/'+ localStorage.getItem("currentUser") +'/me', {
        method: 'GET',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
        }
    })
        .then(response => {
            if (!response.ok) {
                this.setState({
                    isLoadong: false,
                    failed: true
                })
            }
            else {
                response.json().then(user => {
                    this.setState({
                        user: user,
                        isLoadong: false,
                        failed: false
                    })
                });
            }
        })
}

那么为什么模态现在不起作用?如何以正确的方式做到这一点?

标签: javascriptjqueryreactjsmaterial-design

解决方案


您只想在 React 应用程序树结构的叶节点中使用 jQuery。如果这个组件有任何子组件,这是一个坏主意。如果它是一个叶节点组件,那么您将希望将您的 jQuery 逻辑放在 componentDidMount() 函数中。

这个页面有一些关于这个主题的有用材料:https ://reactjs.org/docs/integrating-with-other-libraries.html


推荐阅读