简体   繁体   English

如何使用 React.js 访问标签样式

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

I want to change the background color by changing the page width by conditionally writing, but to do this I need to be able to access the styles我想通过有条件地写入来更改页面宽度来更改背景颜色,但要做到这一点,我需要能够访问样式

If we wanted to write this code in JavaScript, it would be like this:如果我们想用 JavaScript 编写这段代码,应该是这样的:

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

But what if we want to write this code with React and functional method?但是如果我们想用 React 和函数式方法编写这段代码呢?

I would suggest you to do that with css code by simply using media-query.我建议您通过简单地使用媒体查询来使用 css 代码来做到这一点。

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

Docs: https://www.w3schools.com/css/css3_mediaqueries_ex.asp文档: https ://www.w3schools.com/css/css3_mediaqueries_ex.asp

However If you want to dynamically change the style via react you can use the style prop of the element.但是,如果您想通过 react 动态更改样式,则可以使用元素的style属性。 Supposing that the element is a div you can simply do:假设元素是一个 div 你可以简单地做:

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

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

You could write class .backgroundRed and just use condition classes like:您可以编写类 .backgroundRed 并仅使用条件类,例如:

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

or you can directly write styles with style attribute:或者您可以直接使用 style 属性编写样式:

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

you don't have to change the styles with javascript you can just add media query to your styles, for your target devices like:您不必使用 javascript 更改样式您只需将媒体查询添加到您的样式中,对于您的目标设备,例如:

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

}

In this case you have different solutions, but if you want to dynamically change some element style, you can do the following by using the state to store a style object.在这种情况下,您有不同的解决方案,但是如果您想动态更改某些元素样式,可以通过使用状态存储样式对象来执行以下操作。

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>
   )
}

This is speaking of react and element style.这是说反应和元素风格。


In your specific situation, where you want to react to screen size, perhaps a css media query approach would be more efficient.在您想要对屏幕大小做出反应的特定情况下,也许 css 媒体查询方法会更有效。

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

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