我的 JS 文件包含 jQuery (apiCalls.js):
function getBlogInfo() {
$.ajax({
url: "http://api.tumblr.com/v2/blog/myblog.tumblr.com/info?api_key=my-api-key",
dataType: 'jsonp',
success: function(info){
console.log(info);
console.log(info.response.blog.likes);
}
}
)}
export { getBlogInfo };
我的 React 组件:
import React, { Component } from 'react';
import $ from 'jquery';
import { getBlogInfo } from './scripts/apiCalls';
class Homepage extends Component {
componentDidMount(){
getBlogInfo();
}
render() {
return (
<div className="homepage">
</div>
);
}
}
export default Homepage;
如果我将 componentDidMount()
中的 getBlogInfo()
替换为整个脚本,则脚本将按预期执行,但使用函数调用来执行脚本会给出我的错误是 -
./src/components/scripts/apiCalls.js
Line 2: '$' is not defined no-undef
到目前为止我已经尝试过:
在我的所有 React 文件中从“jquery”导入 $。
通过脚本标签导入index.html中的jquery库
最佳答案
尝试在您的 React 项目中添加 jquery npm。
npm install jquery --save
然后像这样使用。
import $ from 'jquery';
关于jquery - 如何在 React 组件中导入 jQuery?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48966808/