简体   繁体   English

将 className 属性添加到 risklySetInnerHTML 内容

[英]Add className attribute to dangerouslySetInnerHTML contents

How to specify className attribute for div which contains 'hello world':如何为包含“hello world”的div指定className属性:

<div dangerouslySetInnerHTML={{__html: '<div>hello world</div>'}} />

One way is to set is to outer div like so:一种方法是设置外部 div,如下所示:

<div dangerouslySetInnerHTML={{__html: '<div>hello world</div>'}} className='class-name'/>

and then in css style the child:然后在 css 风格的孩子:

.class-name div {
  (css stuff here)
}

But I want to set className directly to the div with 'hello world'但我想将className直接设置为带有 'hello world' 的div


EDIT: Adding class name to injected html does not solve the problem, for example:编辑:向注入的 html 添加类名并不能解决问题,例如:

let content = '<div class="class-name">hello world</div>'
<div dangerouslySetInnerHTML={{__html: content}}

does not work, because in case same content is used many times then CSS collisions occur (I am using style-loader with CSS modules on)不起作用,因为如果多次使用相同的内容,则会发生 CSS 冲突(我正在使用带有 CSS 模块的样式加载器)

<div className="post-excerpt" dangerouslySetInnerHTML={{ __html: post.excerpt}}/>

I came across this question after 2 years and I wanted to achieve the exact same results. 2 年后我遇到了这个问题,我想达到完全相同的结果。 I didn't find any accurate answers here but I came up with a solution thanks to @jash8506 due to the brilliant answer to this question .我在这里没有找到任何准确的答案,但由于@jash8506对这个问题的出色回答,我想出了一个解决方案。

We have to utilize two react hooks我们必须使用两个反应钩子

  1. useRef
  2. useLayoutEffect

According to the documentation basically, useRef can be used to access the DOM elements in React and useLayoutEffect can be used to read layout from the DOM and synchronously re-render.根据文档, useRef可用于访问 React 中的 DOM 元素, useLayoutEffect可用于从 DOM 中读取布局并同步重新渲染。

We can access the firstChildElement in the container div and add classes to it's classList我们可以访问firstChildElement容器div ,并添加类到它的classList

Here is how the completed code looks like这是完成的代码的样子

const containerRef = useRef();

useLayoutEffect(()=>{
  if (containerRef.current){
    containerRef.current.firstElementChild.classList.add('class-name');
  }
});

return (
  <div ref={elRef} dangerouslySetInnerHTML={{__html: '<div>hello world</div>'}} />
)

Before you continue reading: Ask yourself why you need dangerouslySetInnerHTML !在继续阅读之前:问问自己为什么需要dangerouslySetInnerHTML This is not meant to be used and if so, use a sanitizer.这并不意味着要使用,如果是这样,请使用消毒剂。

/* React with HTML context */
<div dangerouslySetInnerHTML={{__html: '<div class="class-name">hello world</div>'}} />

You can simplify this however in a safe way:但是,您可以以安全的方式简化此操作:

/* React context only */
<div className="class-name">hello world</div>

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

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