簡體   English   中英

如何使用 React.js 訪問標簽樣式

[英]How to access to tag style with React.js

我想通過有條件地寫入來更改頁面寬度來更改背景顏色,但要做到這一點,我需要能夠訪問樣式

如果我們想用 JavaScript 編寫這段代碼,應該是這樣的:

 document.getElementById("number1").style.backgroundColor="red";

但是如果我們想用 React 和函數式方法編寫這段代碼呢?

我建議您通過簡單地使用媒體查詢來使用 css 代碼來做到這一點。

#number1 {
 @media screen and (min-width: _yourBreakpoint_) {
    background-color: "red";
  }
}

文檔: https ://www.w3schools.com/css/css3_mediaqueries_ex.asp

但是,如果您想通過 react 動態更改樣式,則可以使用元素的style屬性。 假設元素是一個 div 你可以簡單地做:

<div style={{ backgroundColor: width > breakpoint && "red" }}></div>

文檔: https ://reactjs.org/docs/dom-elements.html#style

您可以編寫類 .backgroundRed 並僅使用條件類,例如:

className={width > breakpoint ? '.backgroundRed' : '.elseClass'}

或者您可以直接使用 style 屬性編寫樣式:

style={condition ? {backgroundImage: 'red'} : {} }

您不必使用 javascript 更改樣式您只需將媒體查詢添加到您的樣式中,對於您的目標設備,例如:

/* this is for tablets */
@media only screen and (min-device-width: 768px){
    #number1{
        background-color: 'red';
    }

}

在這種情況下,您有不同的解決方案,但是如果您想動態更改某些元素樣式,可以通過使用狀態存儲樣式對象來執行以下操作。

function MyComponent(props) { 
   // Save your style object in the state
   const [style, setStyle] = useState({background: 'white'});

   // Then just call setStyle when you want to update your style
    
   // I.E. Something like this:
   useEffect(() => {
     window.addEventListener('resize', function () {
          setStyle({...style, background: 'red'});
     })
   }, [])

   // And bind the style to the target element
   return (
     <div style={style}>
        My Content
     </div>
   )
}

這是說反應和元素風格。


在您想要對屏幕大小做出反應的特定情況下,也許 css 媒體查詢方法會更有效。

暫無
暫無

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

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