React中无法访问jQuery插件



我没有成功地将以下jQuery插件导入我的React应用程序:

http://bililite.com/inc/jquery.parsecss.js

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <script src="http://bililite.com/inc/jquery.parsecss.js"></script>
</head>
<body>
<div id="root"></div>
</body>
</html>

我的React组件:

import React, { Component } from "react";
class Main extends Component {
    constructor(props) {
    super(props);
    $.parsecss(".mybutton { color: #ff0000; }", function(css) {
        var x = 0;
        x++;
    });
  }
}

jQuery函数parsecss未定义。

使用脚本标记将其添加到我的index.html中不起作用。只有当将其添加为节点模块并导入时,它才起作用。当然,许多jquery插件无法使用npm,所以我不得不创建自己的包。这其实很简单。在我的node_modules文件夹中,我创建了一个名为parsecss的文件夹和一个子文件夹dist。在dist中,我放置了jquery插件。在parsecss文件夹中,我添加了一个package.json文件,其中包含以下内容:

{
  "main": "dist/jquery.parsecss.js",
  "name": "parsecss",
  "title": "parsecss"
}

您需要添加jQuery,正如我在上面的index.html文件中的示例代码所示:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

在React组件中:

/* global $ */
import React, { Component } from "react";
import parsecss from 'parsecss'
class Main extends Component {
  constructor() {
    $.parsecss(".mybutton { color: #ff0000; }", function(css) {
        var x = 0;
        x++;
    });
  }
}

注意:注释/*global$*/修复了一个控制台错误,该错误指示未定义$。

最新更新