教學課程:使用 React 建立 Power BI 視覺效果

身為開發人員,您可以建立屬於自己的 Power BI 視覺效果。 這些視覺效果可以由您、您的組織,或是第三方使用。

在本教學課程中,您會使用 React 開發 Power BI 視覺效果。 視覺效果會在圓形內顯示已格式化的量值。 視覺效果具有自適性大小,並可讓您自訂其設定。

在本教學課程中,您會了解如何:

  • 為您的視覺效果建立開發專案。
  • 使用 React 開發您的視覺效果。
  • 設定視覺效果以處理資料。
  • 設定視覺效果以適應大小變更。
  • 為您的視覺效果設定自動調整色彩和框線設定。

注意

如需此視覺效果的完整原始程式碼,請參閱 React 圓形卡片 Power BI 視覺效果

必要條件

在您開始開發 Power BI 視覺效果之前,請確認您已具備此節所列的所有項目。

建立開發專案

在本節中,您會為 React 圓形卡片視覺效果建立一個專案。

  1. 開啟 PowerShell 並瀏覽到您要在其中建立專案的資料夾。

  2. 輸入下列命令:

    pbiviz new ReactCircleCard
    
  3. 瀏覽至專案資料夾。

    cd ReactCircleCard
    
  4. 啟動 React 圓形卡片視覺效果。 您的視覺效果現在會在裝載於您電腦上的情況下執行。

    pbiviz start
    

    重要

    若要停止執行視覺效果,請在 PowerShell 中輸入 Ctrl+C,如果系統提示是否要終止批次作業,請輸入 Y,然後按 Enter 鍵。

在 Power BI 服務中檢視 React 圓形卡片

為了在 Power BI 服務中測試視覺效果,我們將使用 US Sales Analysis (美國銷售分析) 報表。 您可以下載 \(英文\) 此報表並將其上傳至 Power BI 服務。

您也可以使用自己的報表來測試視覺效果。

注意

繼續之前,請確認您 已啟用視覺效果開發人員模式

  1. 登入 PowerBI.com,然後開啟 [US Sales Analysis] \(美國銷售分析\) 報表。

  2. 選取編輯

    Power BI 服務 中編輯選項的螢幕快照。

  3. 建立新頁面以供測試使用,然後按一下 Power BI 服務介面底部的 [新增頁面] 按鈕。

    Power BI 服務 中新頁面按鈕的螢幕快照。

  4. 從 [視覺效果] 窗格,選取 [開發人員視覺效果]

    [視覺效果] 窗格中 [開發人員視覺效果] 的螢幕擷取畫面。

    此視覺效果代表您在電腦上執行的自訂視覺效果。 其只有在已啟用自訂視覺效果偵錯設定的情況下才可供使用。

  5. 確認視覺效果已新增至報表畫布。

    新視覺效果已新增至報表的螢幕擷取畫面。

    這是非常簡單的視覺效果,其會顯示已呼叫其更新方法的次數。 在這個階段中,視覺效果尚未擷取任何資料。

    注意

    如果視覺效果顯示連線錯誤訊息,請在瀏覽器中開啟新索引標籤,瀏覽至 https://localhost:8080/assets,並為您的瀏覽器授權以使用此位址。

    新視覺效果顯示連線錯誤的螢幕擷取畫面。

  6. 在已選取新視覺效果的情況下,移至 [資料] 窗格,展開 [Sales] \(銷售\),然後選取 [Quantity] \(數量\)。

    美國銷售分析報表中銷售數據表中 [Power BI 服務 數量] 字段的螢幕快照。

  7. 若要測試視覺效果的回應方式,請調整其大小;請注意,[Update count] \(更新計數\) 的值會隨著您調整視覺效果的大小而遞增。

    新視覺效果的螢幕擷取畫面,其中顯示在調整大小之後不同的更新計數。

在您的專案中設定 React

在本節中,您會了解如何為 Power BI 視覺效果項目設定 React。

開啟 PowerShell,然後輸入 Ctrl+C 來停止執行視覺效果。 如果系統提示您是否要終止批次作業,請輸入 Y,然後按 Enter 鍵。

安裝 React

若要安裝必要的 React 相依性,請在 ReactCircleCard 資料夾中開啟 PowerShell,然後執行下列命令:

npm i react react-dom

安裝 React 類型定義

若要安裝 React 的類型定義,請在 reactCircleCard 資料夾中開啟 PowerShell,然後執行下列命令:

npm i @types/react @types/react-dom

建立 React 應元件類別

請遵循下列步驟來建立 React 元件類別。

  1. 開啟 VS Code,然後瀏覽至 reactCircleCard 資料夾。

  2. 選取 [檔案]>[新增檔案]來建立新的檔案。

  3. 將下列程式碼複製至新檔案。

    import * as React from "react";
    
    export class ReactCircleCard extends React.Component<{}>{
        render(){
            return (
                <div className="circleCard">
                    Hello, React!
                </div>
            )
        }
    }
    
    export default ReactCircleCard;
    
  4. 選取 [另存新檔],然後瀏覽至 src 資料夾。

  5. 將檔案儲存如下:

    • 在 [檔案名稱] 欄位中,輸入 component
    • 從 [存檔類型] 下拉功能表中,選取 [TypeScript React]

將 React 新增至視覺效果檔案

visual.ts 檔案中的程式碼取代為使用 React 啟用的程式碼。

  1. src 資料夾中,開啟 visual.ts,並將檔案中的程式碼取代為下列程式碼:

    "use strict";
    import powerbi from "powerbi-visuals-api";
    
    import DataView = powerbi.DataView;
    import VisualConstructorOptions = powerbi.extensibility.visual.VisualConstructorOptions;
    import VisualUpdateOptions = powerbi.extensibility.visual.VisualUpdateOptions;
    import IVisual = powerbi.extensibility.visual.IVisual;
    
    // Import React dependencies and the added component
    import * as React from "react";
    import * as ReactDOM from "react-dom";
    import ReactCircleCard from "./component";
    
    import "./../style/visual.less";
    
    export class Visual implements IVisual {
    
        constructor(options: VisualConstructorOptions) {
    
        }
    
        public update(options: VisualUpdateOptions) {
    
        }
    }
    

    注意

    由於預設 Power BI TypeScript 設定無法辨識 React tsx 檔案,因此 VS Code 會將 component 醒目提示為錯誤。

  2. 若要轉譯元件,請將目標 HTML 元素新增至 visual.ts。 此元素是 HTMLElement 中傳遞至建構函式的 VisualConstructorOptions

    1. src 資料夾中,開啟 visual.ts

    2. 將下列程式碼新增至 Visual 類別:

    private target: HTMLElement;
    private reactRoot: React.ComponentElement<any, any>;
    
    1. 將下列幾行新增至 VisualConstructorOptions 建構函式:
    this.reactRoot = React.createElement(ReactCircleCard, {});
    this.target = options.element;
    
    ReactDOM.render(this.reactRoot, this.target);
    

    您的 visual.ts 檔案現在應該看起來像這樣:

    "use strict";
    import powerbi from "powerbi-visuals-api";
    
    import DataView = powerbi.DataView;
    import VisualConstructorOptions = powerbi.extensibility.visual.VisualConstructorOptions;
    import VisualUpdateOptions = powerbi.extensibility.visual.VisualUpdateOptions;
    import IVisual = powerbi.extensibility.visual.IVisual;
    import * as React from "react";
    import * as ReactDOM from "react-dom";
    import ReactCircleCard from "./component";    
    
    import "./../style/visual.less";
    
    export class Visual implements IVisual {
        private target: HTMLElement;
        private reactRoot: React.ComponentElement<any, any>;
    
        constructor(options: VisualConstructorOptions) {
            this.reactRoot = React.createElement(ReactCircleCard, {});
            this.target = options.element;
    
            ReactDOM.render(this.reactRoot, this.target);
        }
    
        public update(options: VisualUpdateOptions) {
    
        }
    }
    
  3. 儲存 visual.ts

編輯 tsconfig 檔案

編輯 tsconfig.json 以使用 React。

  1. reactCircleCard 資料夾中,開啟 tsconfig.json 檔案,並將兩行新增至 compilerOptions 項目的開頭。

    "jsx": "react",
    "types": ["react", "react-dom"],
    

    您的 tsconfig.json 檔案現在應該看起來像這樣,而且 component 中的 錯誤應該消失。

    {
        "compilerOptions": {
            "jsx": "react",
            "types": ["react", "react-dom"],
            "allowJs": false,
            "emitDecoratorMetadata": true,
            "experimentalDecorators": true,
            "target": "es6",
            "sourceMap": true,
            "outDir": "./.tmp/build/",
            "moduleResolution": "node",
            "declaration": true,
            "lib": [
                "es2015",
                "dom"
            ]
        },
        "files": [
            "./src/visual.ts"
        ]
    }
    
  2. 儲存 tsconfig.json

測試您的視覺效果

CircleCardVisual 資料夾中開啟 PowerShell,然後執行您的專案:

pbiviz start

當您在 Power BI 服務中將新的開發人員視覺效果新增至報表時,其看起來會像這樣:

此螢幕擷取畫面顯示 Power B I 服務中新建立開發人員視覺效果中的 hello React 訊息。

設定視覺效果的資料欄位

設定視覺效果的功能檔案,以便只有一個資料欄位可以提交至視覺效果的 [量值資料] 欄位。

  1. VS Code 中,從 reactCircleCard 資料夾中開啟 capabilities.json

  2. ReactCircleCard 會顯示單一值,即 Measure Data。 將 Category Data 物件從 dataRoles 移除。

    在移除 Category Data 物件之後, dataRoles 索引鍵看起來像這樣:

    "dataRoles": [
        {
            "displayName": "Measure Data",
            "name": "measure",
            "kind": "Measure"
        }
    ],
    
  3. 移除 objects 索引鍵的所有內容 (您稍後將會填入內容)。

    移除其內容之後,objects 索引鍵看起來像這樣:

    "objects": {},
    
  4. dataViewMappings 屬性取代為以下列程式碼。 max: 1 中的 measure 指定只有一個資料欄位可以提交至視覺效果的 [量值資料] 欄位。

    "dataViewMappings": [
        {
            "conditions": [
                {
                    "measure": {
                        "max": 1
                    }
                }
            ],
            "single": {
                "role": "measure"
            }
        }
    ]
    
  5. 儲存您對 capabilities.json 所做的變更。

  6. 驗證 pbiviz start 是否執行中,並在 Power BI 服務中,重新整理您的「React 圓形卡片」視覺效果。 [量值資料] 欄位只能接受一個資料欄位,如 max: 1 所指定。

    此螢幕擷取畫面顯示 Power BI 服務中 React 圓形卡片中的 [量值資料] 欄位。

更新視覺效果的樣式

在本節中,您會將視覺效果的形狀變成圓形。 使用 visual.less 檔案來控制視覺效果的樣式。

  1. style 資料夾中,開啟 visual.less

  2. visual.less 的內容取代為下列程式碼。

    .circleCard {
        position: relative;
        box-sizing: border-box;
        border: 1px solid #000;
        border-radius: 50%;
        width: 200px;
        height: 200px;
    }
    
    p {
        text-align: center;
        line-height: 30px;
        font-size: 20px;
        font-weight: bold;
    
        position: relative;
        top: -30px;
        margin: 50% 0 0 0;
    }
    
  3. 儲存 visual.less

設定您的視覺效果以從 Power BI 接收屬性

在本節中,您會將視覺效果設定為從 Power BI 接收資料,並將更新傳送至 component.tsx 檔案中的執行個體。

使用 React 轉譯資料

您可以使用 React 來轉譯資料。 元件可以顯示來自其本身狀態的資料。

  1. 在 VS Code 中,從 reactCircleCard 資料夾中開啟 component.tsx

  2. component.tsx 的內容取代為下列程式碼。

    import * as React from "react";
    
    export interface State {
        textLabel: string,
        textValue: string
    }
    
    export const initialState: State = {
        textLabel: "",
        textValue: ""
    }
    
    export class ReactCircleCard extends React.Component<{}, State>{
        constructor(props: any){
            super(props);
            this.state = initialState;
        }
    
        render(){
            const { textLabel, textValue } = this.state;
    
            return (
                <div className="circleCard">
                    <p>
                        {textLabel}
                        <br/>
                        <em>{textValue}</em>
                    </p>
                </div>
            )
        }
    }
    
  3. 儲存 component.tsx

設定您的視覺效果以接收資料

視覺效果會接收資料,作為 update 方法的引數。 在本節中,您會更新此方法以接收資料。

下列程式碼會從 textLabel 選取 textValueDataView,如果資料存在,則會更新元件狀態。

  1. 在 VS Code 中,從 src 資料夾中開啟 visual.ts

  2. 將行 import ReactCircleCard from "./component"; 取代為以下列程式碼:

    import { ReactCircleCard, initialState } from "./component";
    
  3. 將下列程式碼新增至 update 方法。

    if(options.dataViews && options.dataViews[0]){
        const dataView: DataView = options.dataViews[0];
    
        ReactCircleCard.update({
            textLabel: dataView.metadata.columns[0].displayName,
            textValue: dataView.single.value.toString()
        });
    } else {
        this.clear();
    }
    
  4. 將下列程式碼新增至 clear 方法下方來建立 update 方法。

    private clear() {
        ReactCircleCard.update(initialState);
    }
    
  5. 儲存 visual.ts

設定您的視覺效果以傳送資料

在本節中,您會更新視覺效果,將更新傳送至 component 檔案中的執行個體。

  1. 在 VS Code 中,從 src 資料夾中開啟 component.tsx

  2. 將下列程式碼新增至 ReactCircleCard 類別:

    private static updateCallback: (data: object) => void = null;
    
    public static update(newState: State) {
        if(typeof ReactCircleCard.updateCallback === 'function'){
            ReactCircleCard.updateCallback(newState);
        }
    }
    
    public state: State = initialState;
    
    public componentWillMount() {
            ReactCircleCard.updateCallback = (newState: State): void => { this.setState(newState); };
    }
    
    public componentWillUnmount() {
        ReactCircleCard.updateCallback = null;
    }
    
  3. 儲存 component.tsx

檢視視覺效果的變更

測試您的「React 圓形卡片」視覺效果,以檢視您所做的變更。

  1. 驗證 pbiviz start 是否執行中,並在 Power BI 服務中,重新整理您的「React 圓形卡片」視覺效果。

  2. 將 [銷售] 新增至視覺效果的 [量值資料] 欄位。

銷售值的螢幕擷取畫面,此銷售值顯示在 Power BI 服務的 React 圓形卡片視覺效果中。

讓您的視覺效果可可調整大小

目前,您的視覺效果具有固定的寬度與高度。 若要讓視覺效果可調整大小,您必須在 sizecomponent.tsx 檔案中同時定義 變數。 在本節中,您會讓視覺效果可調整大小。

在您完成本節中所述的步驟之後,視覺效果中的圓形直徑將會對應至最小寬度或高度大小,而且您將能夠在 Power BI 服務中調整其大小。

設定 visual.ts 檔案

options 物件取得視覺效果檢視區的目前大小。

  1. 在 VS Code 中,從 src 資料夾中開啟 visual.ts

  2. 插入此程式碼以匯入 IViewport 介面。

    import IViewport = powerbi.IViewport;
    
  3. viewport 屬性新增至 visual 類別。

    private viewport: IViewport;
    
  4. update 方法中,於 ReactCircleCard.update 前面新增下列程式碼。

    this.viewport = options.viewport;
    const { width, height } = this.viewport;
    const size = Math.min(width, height);
    
  5. update 方法的 ReactCircleCard.update 中,新增 size

    size,
    
  6. 儲存 visual.ts

設定 component.tsx 檔案

  1. 在 VS Code 中,從 src 資料夾中開啟 component.tsx

  2. 將下列程式碼新增至 export interface State

    size: number
    
  3. 將下列程式碼新增至 export const initialState: State

    size: 200
    
  4. render 方法中,對程式碼進行下列變更:

    1. size 加入 const { textLabel, textValue, size } = this.state;。 此宣告現在應該看起來像這樣:

      const { textLabel, textValue, size } = this.state;
      
    2. return 上方新增下列程式碼。

      const style: React.CSSProperties = { width: size, height: size };
      
    3. 將第一個「傳回」<div className="circleCard"> 取代為:

      <div className="circleCard" style={style}>
      
  5. 儲存 component.tsx

設定視覺效果檔案

  1. 在 VS Code 中,從 style 資料夾中開啟 visual.less

  2. .circleCard 中,將 widthheight 取代為 min-widthmin-height

    min-width: 200px;
    min-height: 200px;
    
  3. 儲存 visual.less

讓您的 Power BI 視覺效果可自訂

在本節中,您會新增自訂視覺效果的功能,讓使用者可以對其色彩和框線粗細進行變更。

將色彩和粗細新增至功能檔案

將色彩和框線粗細新增至 object 中的 屬性。

  1. 在 VS Code 中,從 reactCircleCard 資料夾中開啟 capabilities.json

  2. 將下列設定新增至 objects 屬性。

    "circle": {
        "properties": {
           "circleColor": {
                "type": {
                    "fill": {
                        "solid": {
                            "color": true
                        }
                    }
                }
            },
            "circleThickness": {
                "type": {
                    "numeric": true
                }
            }
        }
    }
    
  3. 儲存 capabilities.json

將圓形格式化設定類別新增至設定檔案

Circle 格式化設定新增至 settings.ts。 如需如何建置格式化模型設定的詳細資訊,請參閱格式化公用程式

  1. 在 VS Code 中,從 src 資料夾中開啟 settings.ts

  2. settings.ts 設定中的程式碼取代為下列程式碼:

    "use strict";
    
    import { formattingSettings } from "powerbi-visuals-utils-formattingmodel";
    
    import FormattingSettingsCard = formattingSettings.SimpleCard;
    import FormattingSettingsSlice = formattingSettings.Slice;
    import FormattingSettingsModel = formattingSettings.Model;
    
    /**
    * Circle Formatting Card
    */
    class CircleCardSettings extends FormattingSettingsCard {
        circleColor = new formattingSettings.ColorPicker({
            name: "circleColor", // circle color name should match circle color property name in capabilities.json
            displayName: "Color",
            description: "The fill color of the circle.",
            show: true,
            value: { value: "white" }
        });
    
        circleThickness = new formattingSettings.NumUpDown({
            name: "circleThickness", // circle thickness name should match circle color property name in capabilities.json
            displayName: "Thickness",
            description: "The circle thickness.",
            show: true,
            value: 2
        });
    
        name: string = "circle"; // circle card name should match circle object name in capabilities.json
        displayName: string = "Circle";
        show: boolean = true;
        slices: Array<FormattingSettingsSlice> = [this.circleColor, this.circleThickness];
    }
    
    /**
    * visual settings model class
    *
    */
    export class VisualFormattingSettingsModel extends FormattingSettingsModel {
        // Create formatting settings model circle formatting card
        circleCard = new CircleCardSettings();
    
        cards = [this.circleCard];
    }
    
  3. 儲存 settings.ts

新增方法以套用視覺效果設定

新增用來將視覺效果設定和必要匯入套用至 getFormattingModel 檔案的 方法。

  1. 在 VS Code 中,從 src 資料夾中開啟 visual.ts

  2. import 頂端新增這些 陳述式。

    import { FormattingSettingsService } from "powerbi-visuals-utils-formattingmodel";
    import { VisualFormattingSettingsModel } from "./settings";
    
  3. 將下列宣告新增至 [視覺效果]

    private formattingSettings: VisualFormattingSettingsModel;
    private formattingSettingsService: FormattingSettingsService;
    
  4. getFormattingModel 方法新增至 [視覺效果]

    public getFormattingModel(): powerbi.visuals.FormattingModel {
        return this.formattingSettingsService.buildFormattingModel(this.formattingSettings);
    }
    
  5. Visual 類別中,將下列程式碼行新增至 constructor 以初始化 formattingSettingsService

        this.formattingSettingsService = new FormattingSettingsService();
    
    
  6. Visual 類別中,將下列程式碼新增至 update,以將視覺效果格式化設定更新為最新的格式化屬性值。

    1. 將此程式碼新增至 後面的 const size = Math.min(width, height); 陳述式。

      this.formattingSettings = this.formattingSettingsService.populateFormattingSettingsModel(VisualFormattingSettingsModel, options.dataViews[0]);
      const circleSettings = this.formattingSettings.circleCard;
      
    2. 將此程式碼新增至 ReactCircleCard.update 後面的 size

      borderWidth: circleSettings.circleThickness.value,
      background: circleSettings.circleColor.value.value,
      }
      
  7. 儲存 visual.ts

編輯元件檔案

編輯元件檔案,以便其可以轉譯視覺效果色彩和框線粗細的變更。

  1. 在 VS Code 中,從 src 資料夾中開啟 component.tsx

  2. 將這些值新增至 State

    background?: string,
    borderWidth?: number
    
  3. render 方法中,將下列程式碼行:

    1. const { textLabel, textValue, size } = this.state; 取代為:

      const { textLabel, textValue, size, background, borderWidth } = this.state;
      
    2. const style: React.CSSProperties = { width: size, height: size }; 取代為:

      const style: React.CSSProperties = { width: size, height: size, background, borderWidth };
      
  4. 儲存 component.tsx

檢閱變更

實驗視覺效果的色彩和框線粗細,您現在可以控制此色彩和粗細。

  1. 驗證 pbiviz start 是否執行中,並在 Power BI 服務中,重新整理您的「React 圓形卡片」視覺效果。

  2. 選取 [格式] 索引標籤,然後展開 [圓形]

  3. 調整視覺效果的 [色彩] 和 [粗細] 設定,並檢閱其對視覺效果的影響。

Power BI 服務中 React 圓形卡片視覺效果的螢幕擷取畫面,其中顯示色彩和框線粗細格式選項。