【问题标题】:Does Gatsby Offer A Way To Map Generic HTML Elements Rendered From Markdown To React Components?Gatsby 是否提供了一种将 Markdown 渲染的通用 HTML 元素映射到 React 组件的方法?
【发布时间】:2018-10-17 00:03:07
【问题描述】:

我希望能够使用已在我的 Gatsby 站点中定义和使用的组件,用于从 markdown 节点呈现的元素。使用 styled-components 我有多个表示 html 元素的组件:

const PrimaryHeader = styled.h1`…`
const SecondaryHeader = styled.h2`…`
const TextList = styled.ul`…`
etc

是否有一种机制可以将标记中定义的 generic html 元素映射到反应组件,以便标记中定义的值为:

# Example

例如由我的PrimaryHeader 组件渲染。

似乎样式标记的唯一选择是使用后代选择器来定位呈现的降价内容中的元素,当我已经定义了用于呈现这些元素的组件时,这感觉很笨拙和不必要。

注意,Gatsby does support 是自定义组件的映射,但这涉及到将自定义 html 添加到 markdown 中。我希望降价是通用的。

【问题讨论】:

    标签: javascript html markdown styled-components gatsby


    【解决方案1】:

    是的,我已经在 Gatsby 文档中添加了 section,解释了如何在此处复制:

    从通用 HTML 元素映射

    您还可以将通用 HTML 元素映射到您自己的组件之一。如果您使用样式组件之类的东西,这可能特别有用,因为它允许您在降价内容和站点的其余部分之间共享这些原语。这也意味着 Markdown 的作者不需要使用任何自定义标记 - 只需标准 Markdown。 例如,如果您有一系列标题组件:

    const PrimaryTitle = styled.h1`…`
    const SecondaryTitle styled.h2`…`
    const TertiaryTitle styled.h3`…`
    

    您可以将 markdown 中定义的标头映射到这些组件:

    const renderAst = new rehypeReact({
      createElement: React.createElement,
      components: { 
        "h1": PrimaryTitle,
        "h2": SecondaryTitle,
        "h3": TertiaryTitle,
       },
    }).Compiler;
    

    markdown 中定义的标头将呈现为您的组件,而不是通用的 HTML 元素:

    # This will be rendered as a PrimaryTitle component
    ## This will be rendered as a SecondaryTitle component
    ### This will be rendered as a TertiaryTitle component
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-05-11
      • 2021-03-28
      • 1970-01-01
      • 2021-02-22
      • 2015-11-01
      • 2019-05-20
      • 2011-08-29
      相关资源
      最近更新 更多