如何使用React.js访问标签样式
我想通过有条件写作来更改页面宽度来更改背景颜色,但是要这样做,如果我们想在JavaScript中编写此代码,我需要访问样式
,这就是这样:
document.getElementById("number1").style.backgroundColor="red";
但是,如果我们想用React和功能方法编写此代码怎么办?
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:
document.getElementById("number1").style.backgroundColor="red";
But what if we want to write this code with React and functional method?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我建议您通过简单地使用媒体品牌来使用CSS代码来完成此操作。
文档: https://www.www.w3schools.comsss/csss/cssss/css3_mediaqureisequeriesequeries_exp
如果要通过React动态更改样式,则可以使用
样式
元素的道具。假设该元素是您可以简单地做的div:doc: https:https:// reactjs。 org/docs/dom-elements.html#样式
I would suggest you to do that with css code by simply using media-query.
Docs: 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. Supposing that the element is a div you can simply do:Docs: https://reactjs.org/docs/dom-elements.html#style
您不必使用JavaScript更改样式,您只需在样式中添加媒体查询,例如:
you don't have to change the styles with javascript you can just add media query to your styles, for your target devices like:
您可以编写类。backgroundred,只使用条件类,例如:
您可以直接使用样式属性编写样式:
You could write class .backgroundRed and just use condition classes like:
or you can directly write styles with style attribute:
在这种情况下,您有不同的解决方案,但是如果要动态地更改某些元素样式,则可以使用状态存储样式对象来执行以下操作。
这是关于反应和元素样式的。
在您的特定情况下,您想对屏幕尺寸做出反应,也许CSS媒体查询方法会更有效。
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.
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.