Home > Article > Web Front-end > How to write css in react
How to write css in react: 1. Add style to the DOM element of the class name through className; 2. Directly add the style attribute to the corresponding DOM element; 3. By defining global variables to define a css style.
The operating environment of this article: windows7 system, react17.0.1&&css3 version, Dell G3 computer.
How to write css style in react?
In the basic syntax of JSX, there are three main methods on how to write css styles in react
1. Based on class -- (className)
Based on className, through className in In style, add a style to the DOM element of the class name
<style> .title{ color:blue; } </style> <div id='app'></div> //创建一个叫App类,继承(extends)了react中创建组件的方法(component) class App extends React.Component{ constructor(props){ super(peops) } render(){ //类里面负责构建HTML的位置,render渲染 return( //返回HTML结构 <div className="title">高版本</div> ) } } //将虚拟DOM以组件标签的形式渲染到id为'app'的真实DOM之间 ReactDOM.render(<App/>,document.getElementById('app'))
2. Based on inner css (the method advocated by Facebook) interline style (json)
What Facebook advocates is the interline style, directly Add the style attribute to the corresponding DOM element, follow the rules of react, and write it in { }.
<div id='app'></div> class App extends React.Component{ constructor(props){ super(peops) } render(){ return( <div style={{color:'red'}}>hello 行间样式</div> ) } } //将虚拟DOM以组件标签的形式渲染到id为'app'的真实DOM之间 ReactDOM.render(<App/>,document.getElementById('app'))
3. Prototype chain and global variables
You can define a css style by defining global variables, and DOM elements that apply to this style can be called directly.
You need to pay attention to the location of adding styles in the prototype chain. When calling, pass this, this points to the component
<div id='app'></div> //全局样式方法 var color={color:'red'} class App extends React.Component{ constructor(props){ super(peops) } render(){ return( <div style={color}>react全局行间样式</div> //this 指向组件本身 <div style={this.col}>原型样式</div> ) } } //原型链样式的写法,在创建完以及渲染中间的位置添加原型上的样式 App.prototype.col={ color:pink } //将虚拟DOM以组件标签的形式渲染到id为'app'的真实DOM之间 ReactDOM.render(<App/>,document.getElementById('app'))
The above are three ways to write css styles in react. Is there anything missing or incorrect? Any corrections are welcome.
Recommended: "react video tutorial"
The above is the detailed content of How to write css in react. For more information, please follow other related articles on the PHP Chinese website!