如何解决将CSS类传递到完整的块内容根目录
想象一下以下情况:
我从健全CMS检索富文本作为阻止内容。块内容包含一个块,例如可以是<h2>Hello World</h2>
。该HTML是<Blockcontent block={someBlockContent}/>
使用 @ sanity / block-content-to-react 的结果。
我的问题:
是否可以将CSS类传递到该渲染的H2元素中?因此它会呈现为<h2 class="title">Hello World</h2>
吗?我看到了属性 className 和 renderContainerOnSingleChild ,但是这些属性会为该H2元素添加父级。但是我想添加一个CSS类而不添加父DOM。
谢谢!
解决方法
您可以将替代列表传递给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} />
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。