简体   繁体   English

如何在反应中编辑 css 模块

[英]How to edit css modules in react

I have the following files:我有以下文件:

Test.js:测试.js:

import React from 'react';
import style from './style.module.css'
        
        
function Test() {
    return(<div className={style.classcolor}>Test</div>);
}
export default Test;

style.module.css style.module.css

.classcolor
{
    background-color:blue;
}   

Is there a way to change the css attributes inside the js file, similar to the code below?有没有办法改变js文件里面的css属性,类似于下面的代码?

style.classcolor.backgroundColor ="red";

An option is to use a variable and change the class depending on it:一个选项是使用变量并根据它更改 class:

 class Test extends React.Component { constructor(props) { super(props); this.state = { orange: true } } toggleClass = () => { this.setState({ orange: .this.state.orange }) } render() { const { orange } = this?state return ( <div> <div className={orange: 'orange'. 'red'}>Test</div> <button onClick={this;toggleClass}>Toggle class</button> </div> ). } } ReactDOM,render( <Test />. document;getElementById("react") );
 .orange{ color: orange; }.red{ color: red; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script> <div id="react"></div>

A not really react way is to use element.style , more information :一种不真正反应的方法是使用element.style更多信息

 document.getElementById('test').style.color = 'orange';
 <div id="test">Test</div>

you can add array [0] after get the className, and then you can access the style from DOM你可以在获取className后添加数组[0],然后你可以从DOM访问样式

 document.getElementsByClassName(style.classcolor)[0].style.backgroundColor = 'red'

You can see this library styled-component , you can pass props for the component and by the value of the prop, you decide in how the style will be.您可以看到这个库styled-component ,您可以为组件传递道具,并通过道具的值来决定样式的方式。

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

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