Gatsby 将CSS类传递到健全块内容根目录
想象一下以下情况: 我从SanityCMS中检索富文本作为块内容。块内容包含单个块,例如Gatsby 将CSS类传递到健全块内容根目录,gatsby,sanity,Gatsby,Sanity,想象一下以下情况: 我从SanityCMS中检索富文本作为块内容。块内容包含单个块,例如Hello World。此HTML是使用@sanity/block内容进行反应的结果 我的问题: 有没有办法将CSS类传递到呈现的H2元素中?因此,它将呈现为Hello World?我看到了属性className和renderContainerOnSingleChild,但是这些属性会向这个H2元素添加一个父元素。但是我想添加一个CSS类而不添加父DOM 谢谢大家! 您可以将覆盖列表传递给序列化程序属性。对于
Hello World
。此HTML是
使用@sanity/block内容进行反应的结果
我的问题:
有没有办法将CSS类传递到呈现的H2元素中?因此,它将呈现为Hello World
?我看到了属性className和renderContainerOnSingleChild,但是这些属性会向这个H2元素添加一个父元素。但是我想添加一个CSS类而不添加父DOM
谢谢大家! 您可以将覆盖列表传递给
序列化程序
属性。对于H2之类的东西,它将是数组中块
类型的一部分,您可以执行以下操作:
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} />
您可以将覆盖列表传递给
序列化程序
prop。对于H2之类的东西,它将是数组中块
类型的一部分,您可以执行以下操作:
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} />
我希望动态添加类,而不是像这样。我想从其他组件调用,如
。不管它是一个H2还是一个段落。@MucoBey这很好,您可以使用我概述的方法来实现,只需使用React.createElement(props.node.style,{…props,className:“class1 class2”})
而不是重写声明。你也可以用一个变量来定义它,没有任何理智或盖茨比的特别之处。我想从其他组件调用,如
。不管它是一个H2还是一个段落。@MucoBey这很好,您可以使用我概述的方法来实现,只需使用React.createElement(props.node.style,{…props,className:“class1 class2”})
而不是重写声明。你也可以用一个变量来定义它,没有任何理智或盖茨比的特别之处。