我们正在使用 Office UI Fabric React 为 O365 通信站点开发现代 Web 部件。我想使用新的基于 ts 的方法来设计我的组件 (see here) 。一切都运行良好,只是它没有使用其部署到的 SharePoint 网站的当前主题。
我的 Web 部件是使用 SharePoint Web 部件的标准 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
}
};
然后我设置组件的 styles 属性
<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-backgrounds
它使用 ThemeProvider 服务。
关于reactjs - 如何使用新的基于 ts 的样式方法在 spfx webpart 中获取当前主题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54768206/