简体   繁体   English

从React中的危险地设置InnerHTML修改HTML标签

[英]Modify HTML tag from dangerouslySetInnerHTML in React

I am building a Gatsby Blog using React/Gatsby & the Wordpress API. 我正在使用React / Gatsby和Wordpress API构建Gatsby博客。

I render an excerpt of the latest articles on the landing page like so: 我将着陆页上的最新文章摘录如下:

<span
  className="mb-0"
  id="excerpt-wrapper"
  dangerouslySetInnerHTML={{ __html: this.props.post.node.excerpt}
/>

The problem is, my this.props.post.node.excerpt comes with an unwanted wrapping <p> tag. 问题是,我的this.props.post.node.excerpt带有不需要的包装<p>标签。 This tag inherit from Bootstrap CSS as I am using Bootstrap 4 in my whole project, and from the user agent stylesheet. 当我在整个项目中使用Bootstrap 4时,此标记继承自Bootstrap CSS,并且继承自用户代理样式表。

Hence I need to find a way either to : 因此,我需要找到一种方法:

  • get rid of the wrapping p tag 摆脱包装p标签
  • modify the CSS once the excerpt is mounted 摘录安装后修改CSS

I tried the following solution: 我尝试了以下解决方案:

componentDidMount() {
  this.removePTagMargin();
}

removePTagMargin = () => {
  const excerptWrapper = document.querySelector("#excerpt-wrapper");
  excerptWrapper.firstChild.style.marginBottom = "0px !important"
  excerptWrapper.firstChild.style.marginBlockEnd = "0px !important"
}

but it does not work (maybe because it executes before the WP API call is done ?). 但它不起作用(可能是因为它在WP API调用完成之前执行?)。

How can I solve my problem ? 我该如何解决我的问题?

This is assuming the excerpt comes from gatsby-transformer-remark . 这是假设摘录来自gatsby-transformer-remark

You can choose the format of your excerpt in your GraphQL query for the post, it looks like the format you're using is HTML , you want PLAIN : 您可以在文章的GraphQL查询中选择摘要的格式,看起来您正在使用的格式是HTML ,您想要PLAIN

https://www.gatsbyjs.org/packages/gatsby-transformer-remark/#format https://www.gatsbyjs.org/packages/gatsby-transformer-remark/#format

Try modifying your query by putting the format parameter on the excerpt field: 尝试通过将format参数放在excerpt字段中来修改查询:

{
  allMarkdownRemark {
    edges {
      node {
        excerpt(format: PLAIN)
      }
    }
  }
}

Edit: Hacky way of removing the <p> tags due to the inefficiencies in this gatsby-source-wordpress plugin. 编辑:由于此gatsby-source-wordpress插件的效率低下,删除<p>标签的方法很gatsby-source-wordpress

Add a helper called removeParagraphTags this will simply trim the first three chars from the string and the last 4 chars from the string. 添加一个名为removeParagraphTags的助手,该助手将仅修剪字符串中的前三个字符和字符串中的后四个字符。

removeParagraphTags (excerpt) {
  return excerpt.substr(3, excerpt.length - 7)
}

Then you can use this helper when setting the excerpt HTML. 然后,您可以在设置摘录HTML时使用此帮助程序。

dangerouslySetInnerHTML={{
  __html: this.removeParagraphTags(this.props.post.node.excerpt)
}}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM