How to dynamically modify style in react: 1. Add ref to the element whose style needs to be modified, with syntax such as "
The operating environment of this tutorial: Windows 10 system, react18.0.0 version, Dell G3 computer.
How to dynamically modify style in react?
About three ways for React to dynamically modify element styles
React to dynamically modify element styles
Common ways for React to dynamically modify element styles There are two types: modifying the style of the element with the help of ref and dynamically controlling the change of state
1. Using ref to dynamically modify the style
Add ref
## on the element that needs to be modified. #<div className='scroll-title clear-fix' ref={ this.manage }>Add React.createRef() in constructorthis.manage = React.createRef()Use in logic codethis.manage.current.style.display = 'block'if code If this cannot be recognized, you need to change the pointer of this through let that = thisthat.manage.current.style.display = 'block'2. Modify the style of the element through dynamic control of state changes (two methods)Method 1
Set a flag display in the logic code to be true by default, change the value of display to true or false through the corresponding conditions, and then assign the corresponding style name to the DOM The className attribute, the style is written in the corresponding style For example:constructor() { super() this.state = { display: true } } componentDidMount() { window.onscroll = function(event) { if (divTop < -12) { that.setState({ display: false }) that.manage.current.style.display = 'block' } else { that.setState({ display: true }) } } }<div className={this.state.display ? 'none' : 'scroll-title }>Method 2
The implementation principle of method 2 is the same as method 1. Set a flag display in the logic code to be true by default, change the value of display to true or false according to the corresponding conditions, and then assign the corresponding style name to the DOM. className attribute, the style is written in the corresponding style. The difference is that the logic code is not judged in the DOM, but in js, as follows:
3. By using JS code (ternary operator) in DOM
to realize the display and hiding conversion of different DOM
way Third, it is not changing the style in the strict sense, it is just used to change the display, hiding and display of the corresponding components.
Summary:
If the changed styles are more complex, use 2If the changed styles are not too many, use 1 and 2If it is just a switch between two components (display and Hidden) It is most convenient to use 3
React style conflict problemThere is already a sass configuration in the react scaffolding, so you only need to install the sass dependency package and you can use sass directlyInstall the sass dependency package
npm i sass -D- Change index.css to index.scss- Import index. scss fileNote: If scss is used, you need to add ~ when using the absolute path of the image in scssbackground-image: url(~assets/login.png);css-style privatizationcss modules-Basic usageSteps
1. Change the style file name. From xx.scss -> xx.module.scss (convention in React scaffolding, distinguished from ordinary CSS) 2. Introduce and use.Import the style file into the component (note the syntax)
import styles from './index.module.scss'Access the style name in the object through the styles object to set the style
<div className={styles.css類名}></div>css class name is the class name defined in index.module.scss.Example
Define style index.module.css .root {font-size: 100px;}Use style
import styles from './index.module.css' <div className={styles.root}>div的內(nèi)容</div>Principle
CSS Modules ensures the uniqueness of the class name by automatically supplementing the class name with the CSS class name , thereby avoiding the problem of style conflictsNotes on css module
It is best to use camel case naming for class names, because the final class name will generate an attribute of stylescssModules-Maintain class nameFormat
In xxx.module.scss, if you want to maintain the class name, you can use the format: :global(.class name)/*這樣css modules就不會(huì)修改掉類名.a了。等價(jià)于寫在 index.css中 */ :global(.a) { } /* 這樣css modules就不會(huì)修改掉類名.a了, 但是 .aa還是會(huì)被修改 */ .aa :golbal(.a) { }Override the style of third-party components:global(.ant-btn) { color: red !important; }css modules-best practices- The root node of each component uses a class name in the form of CSSModules (class name of the root element: root ) - All other child nodes use ordinary CSS class names: global
index.module.scss
// index.module.scss .root { display: 'block'; position: 'absolute'; // 此處,使用 global 包裹其他子節(jié)點(diǎn)的類名。此時(shí),這些類名就不會(huì)被處理,在 JSX 中使用時(shí),就可以用字符串形式的類名 // 如果不加 :global ,所有類名就必須添加 styles.title 才可以 :global { .title { .text { } span { } } .login-form { ... } } }component usageimport styles from './index.module.scss' const 組件 = () => { return ( {/* (1) 根節(jié)點(diǎn)使用 CSSModules 形式的類名( 根元素的類名: `root` )*/}{/* (2) 所有子節(jié)點(diǎn),都使用普通的 CSS 類名*/}) }登錄 登錄
Recommended learning: "react video tutorial"
The above is the detailed content of How to dynamically modify style in react. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Methods for element.style to modify elements: 1. Modify the background color of the element; 2. Modify the font size of the element; 3. Modify the border style of the element; 4. Modify the font style of the element; 5. Modify the horizontal alignment of the element. Detailed introduction: 1. Modify the background color of the element, the syntax is "document.getElementById("myElement").style.backgroundColor = "red";"; 2. Modify the font size of the element, etc.

ReactRouter User Guide: How to Implement Front-End Routing Control With the popularity of single-page applications, front-end routing has become an important part that cannot be ignored. As the most popular routing library in the React ecosystem, ReactRouter provides rich functions and easy-to-use APIs, making the implementation of front-end routing very simple and flexible. This article will introduce how to use ReactRouter and provide some specific code examples. To install ReactRouter first, we need

PHP, Vue and React: How to choose the most suitable front-end framework? With the continuous development of Internet technology, front-end frameworks play a vital role in Web development. PHP, Vue and React are three representative front-end frameworks, each with its own unique characteristics and advantages. When choosing which front-end framework to use, developers need to make an informed decision based on project needs, team skills, and personal preferences. This article will compare the characteristics and uses of the three front-end frameworks PHP, Vue and React.

Integration of Java framework and React framework: Steps: Set up the back-end Java framework. Create project structure. Configure build tools. Create React applications. Write REST API endpoints. Configure the communication mechanism. Practical case (SpringBoot+React): Java code: Define RESTfulAPI controller. React code: Get and display the data returned by the API.

Vue.js is suitable for small and medium-sized projects and fast iterations, while React is suitable for large and complex applications. 1) Vue.js is easy to use and is suitable for situations where the team is insufficient or the project scale is small. 2) React has a richer ecosystem and is suitable for projects with high performance and complex functional needs.

Netflixusesacustomframeworkcalled"Gibbon"builtonReact,notReactorVuedirectly.1)TeamExperience:Choosebasedonfamiliarity.2)ProjectComplexity:Vueforsimplerprojects,Reactforcomplexones.3)CustomizationNeeds:Reactoffersmoreflexibility.4)Ecosystema

React combines JSX and HTML to improve user experience. 1) JSX embeds HTML to make development more intuitive. 2) The virtual DOM mechanism optimizes performance and reduces DOM operations. 3) Component-based management UI to improve maintainability. 4) State management and event processing enhance interactivity.

The React ecosystem includes state management libraries (such as Redux), routing libraries (such as ReactRouter), UI component libraries (such as Material-UI), testing tools (such as Jest), and building tools (such as Webpack). These tools work together to help developers develop and maintain applications efficiently, improve code quality and development efficiency.
