您可以将覆盖列表传递给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>