簡體   English   中英

將 select2 jquery 組件添加到 SharePoint 框架 (SPFx) Web 部件

[英]Adding select2 jquery component to SharePoint Framework (SPFx) web part

我無法將 Select2 合並到我的 SharePoint web 部件中。 我不確定要從 npm 安裝哪個模塊,或者如何在我的 typescript 文件中包含適當的引用。

使用直接腳本和 css 引用是行不通的,因為它不知道如何解釋啟動:

$(document).ready(function() {
    $('.js-example-basic-single').select2();  <-- fails
});

https://select2.org/getting-started/installation

有一個官方教程解釋了如何在 SPFx 中合並 jQueryUI 手風琴組件。 添加 select2 幾乎是一樣的。

https://learn.microsoft.com/en-us/sharepoint/dev/spfx/web-parts/get-started/add-jqueryui-accordion-to-web-part

其中一種方式:

  1. 添加 jQuery 和 Select2。 @type 文件是可選的(特別是提供自動完成支持),但擁有它們比沒有它們更容易:
> npm i jquery select2 
> npm i @types/jquery @types/select2 --save-dev
  1. 將 jquery 和 seelct2 添加到config/config.json (以便它們包含在 spfx 構建中,即包含在 webpack 中):
  ...
  "externals": {
    "jquery": "node_modules/jquery/dist/jquery.js",
    "select2": "node_modules/select2/dist/js/select2.js"
  },
  ...
  1. 在您的 Web 部件中使用它們。 假設您從“最小”Web 部件開始:
import { Version } from '@microsoft/sp-core-library';
import { BaseClientSideWebPart } from '@microsoft/sp-webpart-base';

import 'jquery';
import 'select2';

import '../../../node_modules/select2/dist/css/select2.css';

export interface IHelloWorldWebPartProps {
}

export default class HelloWorldWebPart 
  extends BaseClientSideWebPart<IHelloWorldWebPartProps> {

  public render(): void {
    this.domElement.innerHTML = `
      <select class="js-example-basic-single" name="state">
        <option value="AL">Alabama</option>
        <option value="WY">Wyoming</option>
      </select>
    `;

    // the below line works now, but breaks the "rule"
    // taht webpart should not go beyond the parent node:
    // 
    //    $(".js-example-basic-single").select2();
    // 
    // using web part root as dropdown parent may be a bit safer:
    // 
    $(".js-example-basic-single").select2({
      dropdownParent: $(this.domElement)
    });
  }

  protected onInit(): Promise<void> {
    return super.onInit();
  }

  protected get dataVersion(): Version {
    return Version.parse('1.0');
  }
}

順便說一句,也許您可以使用Fluent UI組件而不是 Select2,它的樣式將與頁面上的其他 Microsoft 控件相匹配,您將獲得開箱即用的主題支持。 但這當然取決於您項目的性質。

除此之外,您可能希望使用文件的縮小版本(.min.js 和 .min.css)進行生產。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM