【问题标题】:In Tailwind CSS, how to style elements while using dangerouslySetInnerHTML in ReactJS?是否有机会在 dangerouslySetInnerHtml 中设置嵌套的 \"span\"
【发布时间】:2022-11-21 19:46:59
【问题描述】:

我要设置的html是<p>Some text <br/><span>Some text</span>。我想给里面的元素设置一些样式

.我想用顺风设计它。有机会处理这个吗?

【问题讨论】:

    标签: reactjs tailwind-css


    【解决方案1】:

    Tailwind 通常需要在您希望应用样式的元素上设置类。这不是一个好的模式,但您可以使用任意变体和子选择器。

    例如:

    const App = () => {
      const html = '<p>Some text <br/><span>Some text</span>';
    
      return (
        <div
          dangerouslySetInnerHTML={{__html: html}}
          className="[&>p>span]:text-lg"
        />
      );
    }
    

    其他选项可能包括:

    • 定义一个“普通”css 类,将其附加到包装器并在类内设置 span 的样式:

       // index.css
       .wrapper span { 
           color: red;
       }
      
       // react component
       import './index.css';
       ...
       const App = () => {
         const html = '<p>Some text <br/><span>Some text</span>';
      
         return (
           <div
             dangerouslySetInnerHTML={{__html: html}}
             className="wrapper"
           />
         );
       }
      
    • 避免使用 dangerouslySetInnerHTML,找到另一种方法来完全解决这个问题(如果可能的话)

    • 使用 html 解析器(或 DOM)并改变字符串并重新呈现为字符串,或者从结果中呈现反应组件。这是普通 javascript 中的内容(在反应的上下文之外):

       const div = document.createElement('div')
       div.innerHTML = '<p>Some text <br/><span>Some text</span>'
       div.querySelectorAll('span').forEach(span => span.classList.add('text-lg'))
       console.log(div.innerHTML) // <p>Some text <br><span class="text-lg">Some text</span></p>
      

    【讨论】:

      猜你喜欢
      • 2015-02-21
      • 1970-01-01
      • 1970-01-01
      • 2019-05-28
      • 1970-01-01
      • 1970-01-01
      • 2019-03-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多