首页 > 解决方案 > 为什么我看到 webpack 模块 7 不是一个函数?

问题描述

我正在使用 react js,我正在尝试使用 webticker lib webticker

这是我的代码:

$(document).ready(function(){
    $('#webticker').webTicker()
});


class App extends Component {
..... // the rest of the component then in render 

<ul id="webTicker">
    <li>This List Item will scroll infintely</li>
    <li>And this one will follow it</li>
    <li>Finally when it goes out of screen, it will queue again at the end</li>
</ul>

但我得到这个错误

TypeError: jquery__WEBPACK_IMPORTED_MODULE_7___default(...)(...).webTicker is not a function

我已经尝试将其加载componentDidMount并尝试过document.ready,但这也给了我同样的错误。

标签: jqueryreactjswebpack

解决方案


将 JQuery 和 React 一起使用从来都不是一个好主意,因此该解决方案将尝试让它们分开操作。

考虑到 React 会将自己附加到 DOM 中的特定 div,我们可以将我们的 webticker 作为它的兄弟。

例如

<!-- React attaches to this -->
<div id="root"></div>

<!-- Web Ticker attaches to this -->
<ul id="webTicker" style="display:none">
    <li>This List Item will scroll infintely</li>
    <li>And this one will follow it</li>
    <li>Finally when it goes out of screen, it will queue again at the end</li>
</ul>

<!-- Don't forget to load scripts -->
<script src="./path/to/jquery.min.js"></script>
<script src="./path/to/jquery.webticker.min.js"></script>
<script src="./path/to/your/scripts.js></script>

现在您只想在 React 已加载时显示该列表,因此您可以执行类似的操作

$(document).ready(function(){
    if ($('#root').children().length > 0) {
        $('#webticker')
          .show()
          .webTicker()
    }
});

推荐阅读