0

想象以下情况:

我从健全的 CMS 中检索富文本作为块内容。块内容包含单个块,例如<h2>Hello World</h2>. 这个 HTML 是<Blockcontent block={someBlockContent}/>使用@sanity/block-content-to-react的结果。

我的问题:

有没有办法将 CSS 类传递给呈现的 H2 元素?所以它会呈现像<h2 class="title">Hello World</h2>?我看到了属性classNamerenderContainerOnSingleChild,但它们会为这个 H2 元素添加一个父级。但我想添加一个 CSS 类而不添加父 DOM。

谢谢你!

4

1 回答 1

3

您可以将覆盖列表传递给serializers道具。对于像 H2 这样的东西,它是block数组中类型的一部分,你可以这样做:

import BlockContent from "@sanity/block-content-to-react"

const overrides = {
  h2: props => <h2 className="title" {...props} />,
}

const serializers = {
  types: {
    block: props =>
      // Check if we have an override for the “style”
      overrides[props.node.style] 
        // if so, call the function and pass in the children, ignoring
        // the other unnecessary props
        ? overrides[props.node.style]({ children: props.children })

        // otherwise, fallback to the provided default with all props
        : BlockContent.defaultSerializers.types.block(props),
  }
}

const SomeComponent = () => 
  <BlockContent blocks={...} serializers={serializers} />

编辑:自从回答这个问题后,我创作并发布了一个名为react-portable-text的库,以使在 React 中使用 Sanity 的块内容更容易。这是上面使用的react-portable-text代替:

import PortableText from "react-portable-text"

const SomeComponent () => 
  <PortableText content={blockContent} serializers={{ h2: Heading }} />

const Heading = ({ children }) => 
  <h2 className="title">{children}</h2>
于 2020-08-24T17:35:51.650 回答