简体   繁体   中英

How to edit css modules in react

I have the following files:

Test.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

.classcolor
{
    background-color:blue;
}   

Is there a way to change the css attributes inside the js file, similar to the code below?

style.classcolor.backgroundColor ="red";

An option is to use a variable and change the class depending on it:

 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 :

 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

 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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