我一直在读各种文章,包括这篇
use jquery functions within spfx webpart
但我似乎无法让jQuery与我的SPFx Web部件配合使用。
我的第一次尝试是将加载置于全局范围:
public constructor() {
super();
SPComponentLoader.loadCss('https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css');
SPComponentLoader.loadCss('https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css');
SPComponentLoader.loadScript('https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js', { globalExportsName: 'jQuery' }).then((jQuery: any): void => {
SPComponentLoader.loadScript('https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.0/js/bootstrap.min.js', { globalExportsName: 'jQuery' }).then((): void => {
});
});
}
尽管在构造函数中,但上面的代码会在我的呈现函数中导致错误(
未定义jQuery
):
public render(): void {
this.domElement.innerHTML = /* etc...*/
const webpart: ContactFormSimpleWebPartWebPart = this;
// assign handlers
jQuery('#btn-submit-contact-form-simple').on('click', function() {
webpart.SubmitContactFormSimple();
});
// assign vars
this.Category = jQuery('#sel-category');
this.Message = jQuery('#txt-message');
this.ErrorContainer = jQuery('#div-contact-form-simple-errors');
}
接下来,我尝试添加版本2的类型(据我所知,这是SPFx支持的最高版本):
npm安装@类型/jquery@2.0.48--保存开发
"externals": {
"jquery": {
"path": "https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js",
"globalName": "jQuery"
}
},
上述情况会导致许多编译错误,如下所示:
ReferenceError:未定义jQuery
我甚至尝试将其直接添加到渲染中,这不会导致任何错误,除非什么都没有发生!不会显示结果HTML。“”:
public render(): void {
SPComponentLoader.loadScript('https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js', { globalExportsName: 'jQuery' }).then((jQuery: any): void => {
SPComponentLoader.loadScript('https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.0/js/bootstrap.min.js', { globalExportsName: 'jQuery' }).then((): void => {
this.domElement.innerHTML = /* etc...*/
const webpart: ContactFormSimpleWebPartWebPart = this;
// assign handlers
jQuery('#btn-submit-contact-form-simple').on('click', function() {
webpart.SubmitContactFormSimple();
});
// assign vars
this.Category = jQuery('#sel-category');
this.Message = jQuery('#txt-message');
this.ErrorContainer = jQuery('#div-contact-form-simple-errors');
});
});
}
我甚至尝试在init上添加它:
protected onInit(): Promise<void> {
SPComponentLoader.loadCss('https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css');
SPComponentLoader.loadCss('https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css');
SPComponentLoader.loadScript('https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js', { globalExportsName: 'jQuery' }).then((jQuery: any): void => {
SPComponentLoader.loadScript('https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.0/js/bootstrap.min.js', { globalExportsName: 'jQuery' }).then((): void => {
});
});
return Promise.resolve(undefined);
}
我还可以尝试在SPFx Web部件中使用jQuery吗?
编辑:
当我尝试
import * as jQuery from 'jQuery'
我收到以下错误: