如何在流利 UI/React/ts 中正确设置组件样式?

How do I correctly style a component in fluent UI/React/ts?

我正在尝试为此添加背景色 div:

import * as React from 'react'
import { Itest } from '../../../../../models'
import { getPreviewStyles } from './preview.style.ts'

type IPreviewProps = Itest

const PreviewC: React.FunctionComponent<IPreviewProps> = (props: IPreviewProps) => {
  console.log(props)
  return (
    <div>
      <h1 className="base">test test</h1>
      <p>testing testing</p>
      <img src="workingAtComputer.jpg"></img>
    </div>
  )
}

export const Preview = PreviewC

这里我尝试添加紫色的背景色:

import { IStyle } from 'office-ui-fabric-react'

export interface IPreviewStyles {
  base: IStyle
}

export const getPreviewStyles = (): IPreviewStyles => {
  return {
    base: {
      backgroundColor: 'purple',
    }
}

我在第一个文件中收到此错误:“已声明 'getPreviewStyles' 但从未读取其值。”如何将样式应用到类名为“base”的 div?请协助。谢谢

您可能想要实施 css-in-js,但为此您需要使用 Merge styles,它与 Office Fabric UIFluentUI 一起作为较新的版本。

Preview.style.ts:


import { mergeStyleSets } from '@fluentui/merge-styles';

export interface IPreviewStyles {
  base: string;
}

export const getPreviewStyles = (): IPreviewStyles => {
  return mergeStyleSets({
    base: {
      background: 'purple',
    },
  });
};

组件:

import * as React from 'react'
import { Itest } from '../../../../../models'
import { getPreviewStyles } from './preview.style.ts'

type IPreviewProps = Itest

const PreviewC: React.FunctionComponent<IPreviewProps> = (props: IPreviewProps) => {

  const { base } = getPreviewStyles()

  return (
    <div>
      <h1 className={base}>test test</h1>
      <p>testing testing</p>
      <img src="workingAtComputer.jpg"></img>
    </div>
  )
}

export const Preview = PreviewC

您可以阅读有关合并样式的更多信息API here. And my recommendation for you is to switch on latest version of FluentUI