簡體   English   中英

在 React 中動態創建 css 類

[英]Dynamically create css classe in React

我需要使用基於輸入圖像的媒體查詢創建一個 CSS class。 創建 css 的反應腳本應該看起來像這樣:

  const getBackgroungImageSet = (image) => {
    return `.mycontainer {    
                background-image:url("${image}?mw=500"); // big image   
            }
            
            @media(max-width: 768px){
              .mycontainer {
                    background-image:url("${image}?mw=250"); // small image  
                }
            }`;
  }

是否可以將這個class添加到react中的文檔中?

這是一種通過樣式標簽添加 styles 的方法。 實際方法基於React Helmet文檔中顯示的內容。 這是將樣式標簽添加到文檔頭部而不是任意放置在 dom 中間的好方法。

對於樣式標簽,您需要使用type="text/css"並使用字符串,這樣就不會出現由於 CSS 語法在 JSX 中無效而導致的語法錯誤。

 function Example() { return ( <div> <span>This should be purple</span> <br/> <span>This should have a blue border</span> <style type="text/css">{` span { color: purple; } span:nth-of-type(2){ color: inherit; border: 2px solid blue; } `}</style> </div> ); } ReactDOM.render(<Example />, document.getElementById('root'));
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.13.1/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.13.1/umd/react-dom.production.min.js"></script> <div id="root"/>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM