繁体   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