4

我目前正在为 MS Teams 开发应用程序。在习惯了 MS UI 库(现在称为 fluent-ui)之后,一切都开始组装在一起。由于我想为我的用户提供“内置”体验,我想使用微软也使用的本地主题和样式。

作为基础,我使用@fluentui/react-northstar,这是官方支持的团队在这里查看。最好的是,它为船上的团队提供了内置主题。惊人的。

到目前为止,一切都很好。我还想显示一些列表,其中显示了当前登录用户的数据。为此,我想使用Shimmer-DetailsList。这里的问题是我无法应用来自@fluentui/react-northstar 的主题,这让我非常抓狂。有人知道我可以在这里做什么吗?这让我完全发疯,提供的 UI 彼此不兼容,或者我没有使用正确的方法。

如果需要,我也可以显示一些代码,但在这种状态下,我只是想理解。

非常感谢你们的帮助!

最好的,汤姆

更新: 好的可能会有点复杂,但我会尽力展示我的代码。我会缩短不必要的部分。代码是为 React 编写的。

Index.js 我在这里确定用户当前活动的主题,可以通过window.location.search. 然后主题也作为道具传递给 App.js。

import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter } from 'react-router-dom';
import App from './App';
import * as serviceWorker from './serviceWorker';
import { Provider, themes } from '@fluentui/react-northstar'

...

const teamsTheme =  updateTheme(getQueryVariable('theme'));
//const baseUrl = document.getElementsByTagName('base')[0].getAttribute('href');
const rootElement = document.getElementById('root');
console.log("theme in index: " + teamsTheme);
ReactDOM.render(
    <Provider theme={teamsTheme}>
        <App theme={teamsTheme}/>
    </Provider>,
    rootElement
);

App.js 在 App.js 中,我确定了一些通用的东西。我检查 Teams 是否可以对用户进行身份验证,以及用户是否在首次使用时接受了 TOU(针对我的 API 进行查询)。如果一切正常,我会渲染一个名为 content 的自定义组件,我还将主题作为道具传递。我会留下一般的函数声明,因为它们目前没有引起问题。

import React, { Component } from 'react';
import TouService from "./services/touService";
import { Stack } from 'office-ui-fabric-react'
import { Loader } from '@fluentui/react-northstar'
import "./css/settings.css"
import Content from "./components/Content"
import AcceptTou from "./components/AcceptTou"
const microsoftTeams = require('@microsoft/teams-js');

export default class App extends Component {
    static displayName = App.name;

    constructor(props) {
        super(props)

        this.touService = new TouService();

        this.state = {
            userIsAuthenticated: false,
            authenticationLoading: true,
            authMessage: "Unauthorized!!!",
            currentUser: "",
            tokenString: "",
            touAccepted: false,
            touLoading: true
        };

        **some functions here**

    componentDidMount() {
        this.initializeTeams();
    }

    render() {
        const loading = (this.state.authenticationLoading || this.state.touLoading || (this.state.touAccepted === false)) ?
            <div>
                <br />
                <Loader label='Loading...' />
                <br />
            </div> :
            <Content theme={this.props.theme}/>;

        const tou = (this.state.userIsAuthenticated && !this.state.authenticationLoading && !this.state.touLoading && !this.state.touAccepted) &&
            <AcceptTou currentUser={this.state.currentUser} touAccepted={this.state.touAccepted} theme={this.props.theme} onTouChange={this.touAcceptedChanged}/>;

        //console.logconsole.log(this.state);

        return (
            <Stack
                horizontalAlign="center"
                verticalFill
                styles={{
                    root: {
                        width: this.width,
                        height: this.height,
                        margin: '0 auto',
                        textAlign: 'center',
                        color: '#605e5c'
                    }
                }}>
                {loading}
                {tou}
            </Stack>
        );
    }
}

Content.js 在内容中,我确定页面布局的一般内容。

import React, { Component } from 'react';
import AssetMenu from "../UI/AssetMenu"
import Layout from "../UI/Layout"
import ToolbarMenu from '../UI/ToolbarMenu';
import ShimmerApplicationExample from "./List"

export default class Content extends React.Component {
    constructor(props) {
        super(props)
        console.log("theme in content.js: " + this.props.theme);
    }
    render() {
        const content = "my Content";
        return (
            <Layout header={<AssetMenu />} toolbar={<ToolbarMenu />} content={<ShimmerApplicationExample theme={this.props.theme}/>} />
        );
    }
}

Layout.js处理页面的一般布局。目前这并不理想,因为我仍在学习,但这可以稍后完成。

import React from 'react';
import { Flex, Segment, Divider } from '@fluentui/react-northstar'

export default class Layout extends React.Component {

    //<Grid columns="repeat(3, 1fr)" rows="50px 150px 50px">
    render() {
        return (
            <Flex column fill>
                {this.props.header}
                {this.props.toolbar}
                <Segment content={this.props.content} />
            </Flex>
        );
    }
}

ToolbarMenu.js提供了一个工具栏供用户交互或创建一些内容。但是还没有功能。

import React from 'react';
import { Menu, menuAsToolbarBehavior } from '@fluentui/react-northstar';

const items = [
    {
        key: 'add',
        icon: {
            name: 'add',
            outline: true,
        },
        content: "New",
        'aria-label': 'add',
    },
    {
        key: 'edit',
        icon: {
            name: 'edit',
            outline: true,
        },
        content: "Edit",
        'aria-label': 'Edit Tool',
    },
    {
        key: 'delete',
        icon: {
            name: 'trash-can',
            outline: true,
        },
        content: "Delete",
        'aria-label': 'Delete Tool',
    },
];

export default class ToolbarMenu extends React.Component {
    render() {
        return (
            <Menu
                defaultActiveIndex={0}
                items={items}
                primary
                iconOnly
                accessibility={menuAsToolbarBehavior}
                aria-label="Compose Editor"
            />
        )
    }
}

List.tsx应为用户内容提供详细信息列表。这是当前问题所在。代码基本上是 MS这里的示例: . 除了我尝试在不起作用的列表中使用 Index.js 中的主题。

import * as React from 'react';
import { Async } from 'office-ui-fabric-react/lib/Utilities';
import { createListItems, IExampleItem } from '@uifabric/example-data';
import { IColumn, buildColumns, SelectionMode, Toggle } from 'office-ui-fabric-react/lib/index';
import { ShimmeredDetailsList } from 'office-ui-fabric-react/lib/ShimmeredDetailsList';

const fileIcons: { name: string }[] = [
  { name: 'accdb' },
  { name: 'csv' },
  { name: 'docx' },
  { name: 'dotx' },
  { name: 'mpt' },
  { name: 'odt' },
  { name: 'one' },
  { name: 'onepkg' },
  { name: 'onetoc' },
  { name: 'pptx' },
  { name: 'pub' },
  { name: 'vsdx' },
  { name: 'xls' },
  { name: 'xlsx' },
  { name: 'xsn' }
];

const ITEMS_COUNT = 200;
const INTERVAL_DELAY = 2500;

let _items: IExampleItem[];

export interface IShimmerApplicationExampleState {
  items: IExampleItem[]; // DetailsList `items` prop is required so it expects at least an empty array.
  columns?: IColumn[];
  isDataLoaded?: boolean;
}

interface IShimmerListProps {
  theme?: any;
}

export default class ShimmerApplicationExample extends React.Component<IShimmerListProps, IShimmerApplicationExampleState> {
  private _lastIntervalId: number = 0;
  private _lastIndexWithData: number = 0;
  private _async: Async;

  constructor(props: {}) {
    super(props);

    this.state = {
      items: [],
      columns: _buildColumns(),
      isDataLoaded: false
    };

    this._async = new Async(this);
    console.log("theme in shimmer list consturctor: " + this.props.theme);
  }

  public componentWillUnmount(): void {
    this._async.dispose();
  }

  public render(): JSX.Element {
    const { items, columns, isDataLoaded } = this.state;
    const theme = this.props.theme;
    return (
      <div>
        <Toggle
          theme = {theme}
          label="Toggle to load content"
          style={{ display: 'block', marginBottom: '20px' }}
          checked={isDataLoaded}
          onText="Content"
          offText="Shimmer"
        />
        <div>
          <ShimmeredDetailsList
            theme = {theme}
            setKey="items"
            items={items}
            columns={columns}
            selectionMode={SelectionMode.none}
            enableShimmer={!isDataLoaded}
            ariaLabelForShimmer="Content is being fetched"
            ariaLabelForGrid="Item details"
            listProps={{ renderedWindowsAhead: 0, renderedWindowsBehind: 0 }}
          />
        </div>
      </div>
    );
  }

  private _loadData = (): void => {
    this._lastIntervalId = this._async.setInterval(() => {
      const randomQuantity: number = Math.floor(Math.random() * 10) + 1;
      const itemsCopy = this.state.items!.slice(0);
      itemsCopy.splice(
        this._lastIndexWithData,
        randomQuantity,
        ..._items.slice(this._lastIndexWithData, this._lastIndexWithData + randomQuantity)
      );
      this._lastIndexWithData += randomQuantity;
      this.setState({
        items: itemsCopy
      });
    }, INTERVAL_DELAY);
  };

  private _onLoadData = (ev: React.MouseEvent<HTMLElement>, checked: boolean): void => {
    if (!_items) {
      _items = createListItems(ITEMS_COUNT);
      _items.map((item: IExampleItem) => {
        const randomFileType = this._randomFileIcon();
        item.thumbnail = randomFileType.url;
      });
    }

    let items: IExampleItem[];
    const randomQuantity: number = Math.floor(Math.random() * 10) + 1;
    if (checked) {
      items = _items.slice(0, randomQuantity).concat(new Array(ITEMS_COUNT - randomQuantity));
      this._lastIndexWithData = randomQuantity;
      this._loadData();
    } else {
      items = [];
      this._async.clearInterval(this._lastIntervalId);
    }
    this.setState({
      isDataLoaded: checked,
      items: items
    });
  };

  private _onRenderItemColumn = (item: IExampleItem, index: number, column: IColumn): JSX.Element | string | number => {
    if (column.key === 'thumbnail') {
      return <img src={item.thumbnail} />;
    }

    return item[column.key as keyof IExampleItem];
  };

  private _randomFileIcon(): { docType: string; url: string } {
    const docType: string = fileIcons[Math.floor(Math.random() * fileIcons.length) + 0].name;
    return {
      docType,
      url: `https://static2.sharepointonline.com/files/fabric/assets/brand-icons/document/svg/${docType}_16x1.svg`
    };
  }
}

function _buildColumns(): IColumn[] {
  const _item = createListItems(1);
  const columns: IColumn[] = buildColumns(_item);

  for (const column of columns) {
    if (column.key === 'thumbnail') {
      column.name = 'FileType';
      column.minWidth = 16;
      column.maxWidth = 16;
      column.isIconOnly = true;
      column.iconName = 'Page';
      break;
    }
  }

  return columns;
}


为了更好地理解:微软表示这个(fluentui/react-northstar)最适合团队支持,因为它拥有一切,并且还集成了团队主题,但它没有提供作为 office-ui-react 的详细信息列表(应该在事实上几乎相同的库?)而且它们彼此也不兼容?

我不知道我做错了什么,如果可能的话,我宁愿不定义自己的主题,也不愿使用已有的主题。

4

0 回答 0