如何使用新的基于TS的样式方法在SPFX WebPart中获取当前主题



我们正在使用Office UI Fabric React为O365通信站点开发现代WebParts。我想使用新的基于TS的方法来造型我的组件(请参阅此处)。一切正常,除了它不使用部署到的SharePoint网站的当前主题。

我的WebPart是使用SharePoint WebParts的标准Yeoman脚手架创建的(选择React作为框架)。

我的样式代码看起来像这样:

import { getTheme, FontWeights, mergeStyleSets } from 'office-ui-fabric-react/lib/Styling';
export interface IComponentClassNames {
    locationBanner: string;
    locationLabel: string;
    locationValue: string;
    editLocationButton: string;
    findLocationButton: string;
}
const theme = getTheme();
export const getClassNames = (): IComponentClassNames => {
    return mergeStyleSets({
        locationBanner: {
            display: 'inline-flex',
            paddingLeft: '8px',
        },
        locationLabel: [
            theme.fonts.large,
            {
                color: theme.palette.neutralPrimary
            }
        ],
        locationValue: {
            color: theme.palette.themeDark
        },
        editLocationButton: {
            paddingLeft: '20px'
        },
        findLocationButton: {
            paddingLeft: '10px'
        }
    });
};

,然后在组件的渲染部分中进行以下操作:

const {locationBanner, editLocationButton, findLocationButton, locationLabel, locationValue} = getClassNames();

,然后将其应用于className-attributes。这可以正常运行,并且应用样式 - 但是:getTheme()返回默认主题(即主要是蓝色),而不是SharePoint网站上当前设置的内容。我是否必须以某种方式将主题传递给我的组件(来自WebPart TS),或者该如何工作?

我的解决方案是从窗口对象中拉出主题,构建主题对象,然后根据需要将其传递到组件

这样:

在根TS文件

上构建主题
const ThemeColorsFromWindow: any = (window as any).__themeState__.theme;
const siteTheme: ITheme = createTheme({ //pass this object to your components
  palette: ThemeColorsFromWindow
});

然后我将主题传递给需要的组件。

<MyButton
    ButtonText={this.props.itemButtonText}
    ButtonType={'dark'}
    ButtonURL={this.props.itemButtonURL}
    siteTheme={siteTheme} //site theme is passed to component
/>

构建我的CSS-IN-JS对象

  const siteTheme: IReadonlyTheme = this.props.siteTheme; //shortening the path a little
  ButtonStyles: IButtonStyles = { //the interface here varies by component
    root:{
      backgroundColor: siteTheme.palette.themeTertiary, //get theme colors like this
    },
    label:{
      color: siteTheme.palette.white,
    },
    rootHovered:{
      backgroundColor: siteTheme.palette.themePrimary,
    },
    labelHovered:{
      color: siteTheme.palette.white
    }
  };

然后我设置了组件的样式

<PrimaryButton
    styles={ButtonStyles} //pass the styles to the component here
    onClick={() => GoToPage(this.props.ButtonURL)}
    text={this.props.ButtonText ? this.props.ButtonText : 'BUTTON TEXT'}
/>

如果您想调整到变体或部分背景,请查看此博客文章。https://learn.microsoft.com/en-us/sharepoint/dev/spfx/web-parts/guidance/supporting-section-section-backgrounds

使用ThemeProvider服务。

在我看来,就像您正在使用Office-ui-fabric-react库一样。您导入的GetTheme方法来自那里。我看不到如何对当前主题查询Office-ui-fabric-fabric-reactions SharePoint。它可能正在跟踪自己的。我会尝试通过SharePoint组件库来获取主题。https://learn.microsoft.com/en-us/javascript/api/sp-component-base/themeprovider

最新更新