在 React 中修改 dangerouslySetInnerHTML 中的 HTML 标签
Modify HTML tag from dangerouslySetInnerHTML in React
我正在使用 React/Gatsby 和 Wordpress API 构建一个 Gatsby 博客。
我在着陆页上呈现最新文章的摘录,如下所示:
<span
className="mb-0"
id="excerpt-wrapper"
dangerouslySetInnerHTML={{ __html: this.props.post.node.excerpt}
/>
问题是,我的 this.props.post.node.excerpt
带有不需要的包装 <p>
标签。这个标签继承自 Bootstrap CSS 因为我在我的整个项目中使用 Bootstrap 4 和用户代理样式表。
因此我需要找到一种方法来:
- 摆脱包装 p 标签
- 安装摘录后修改CSS
我尝试了以下解决方案:
componentDidMount() {
this.removePTagMargin();
}
removePTagMargin = () => {
const excerptWrapper = document.querySelector("#excerpt-wrapper");
excerptWrapper.firstChild.style.marginBottom = "0px !important"
excerptWrapper.firstChild.style.marginBlockEnd = "0px !important"
}
但它不起作用(可能是因为它在 WP API 调用完成之前执行?)。
我该如何解决我的问题?
这是假设摘录来自 gatsby-transformer-remark
。
您可以在 post 的 GraphQL 查询中选择摘录的格式,看起来您使用的格式是 HTML
,您想要 PLAIN
:
https://www.gatsbyjs.org/packages/gatsby-transformer-remark/#format
尝试通过将 format
参数放在 excerpt
字段来修改您的查询:
{
allMarkdownRemark {
edges {
node {
excerpt(format: PLAIN)
}
}
}
}
编辑:由于此 gatsby-source-wordpress
插件效率低下,删除 <p>
标签的 Hacky 方法。
添加一个名为 removeParagraphTags
的助手,这将简单地 trim 字符串中的前三个字符和字符串中的最后 4 个字符。
removeParagraphTags (excerpt) {
return excerpt.substr(3, excerpt.length - 7)
}
那么在设置摘录的时候就可以使用这个助手了HTML。
dangerouslySetInnerHTML={{
__html: this.removeParagraphTags(this.props.post.node.excerpt)
}}
我正在使用 React/Gatsby 和 Wordpress API 构建一个 Gatsby 博客。
我在着陆页上呈现最新文章的摘录,如下所示:
<span
className="mb-0"
id="excerpt-wrapper"
dangerouslySetInnerHTML={{ __html: this.props.post.node.excerpt}
/>
问题是,我的 this.props.post.node.excerpt
带有不需要的包装 <p>
标签。这个标签继承自 Bootstrap CSS 因为我在我的整个项目中使用 Bootstrap 4 和用户代理样式表。
因此我需要找到一种方法来:
- 摆脱包装 p 标签
- 安装摘录后修改CSS
我尝试了以下解决方案:
componentDidMount() {
this.removePTagMargin();
}
removePTagMargin = () => {
const excerptWrapper = document.querySelector("#excerpt-wrapper");
excerptWrapper.firstChild.style.marginBottom = "0px !important"
excerptWrapper.firstChild.style.marginBlockEnd = "0px !important"
}
但它不起作用(可能是因为它在 WP API 调用完成之前执行?)。
我该如何解决我的问题?
这是假设摘录来自 gatsby-transformer-remark
。
您可以在 post 的 GraphQL 查询中选择摘录的格式,看起来您使用的格式是 HTML
,您想要 PLAIN
:
https://www.gatsbyjs.org/packages/gatsby-transformer-remark/#format
尝试通过将 format
参数放在 excerpt
字段来修改您的查询:
{
allMarkdownRemark {
edges {
node {
excerpt(format: PLAIN)
}
}
}
}
编辑:由于此 gatsby-source-wordpress
插件效率低下,删除 <p>
标签的 Hacky 方法。
添加一个名为 removeParagraphTags
的助手,这将简单地 trim 字符串中的前三个字符和字符串中的最后 4 个字符。
removeParagraphTags (excerpt) {
return excerpt.substr(3, excerpt.length - 7)
}
那么在设置摘录的时候就可以使用这个助手了HTML。
dangerouslySetInnerHTML={{
__html: this.removeParagraphTags(this.props.post.node.excerpt)
}}