Home  >  Article  >  Web Front-end  >  How to add styles to react components

How to add styles to react components

藏色散人
藏色散人Original
2020-11-23 10:43:063572browse

Methods for adding styles to react components: 1. By passing in style objects through expressions; 2. By using inline styles; 3. Defining class names through third-party packages; 4. Through style components" styled-components" to add styles.

How to add styles to react components

The operating environment of this tutorial: windows7 system, React16 version. This method is suitable for all brands of computers.

Four ways to add styles to React components:

DOM style in the component

First: Inline style

Think To add inline styles to the virtual dom, you need to use an expression to pass in the style object:

// 注意这里的两个括号,第一个表示我们在要JSX里插入JS了,第二个是对象的括号
 <p style={{color:&#39;red&#39;, fontSize:&#39;14px&#39;}}>Hello world</p>

Inline styles need to write a style object, and the position of this style object can be placed in many places, such as render In functions, component prototypes, and external link js files

The second type: className (external reference)

React recommends that we use inline styles, because React thinks that each component is an independent The overall

In fact, in most cases we still add a lot of class names to elements, but it should be noted that class needs to be written as className (because after all, we are writing js-like code, and we will receive js rules restrictions, and class is a keyword)

<p className="hello" style = {this.style}>Hello world</p>

The third type: classname/classnames third-party package definition class name

Sometimes it is necessary to add different styles according to different conditions, such as: completion status , completed is green, unfinished is red. In this case, we recommend using the classname/classnames package:

<p
    className = { 
        classname({
            size: true,
            bg: true
        })
    }
> 第三包classname定义 </p>

Fourth: Styled-components

styled-components is a set of css written for React -in-js framework, simply speaking, is writing css in js. npm link

styled-components is a third-party package, it needs to be installed

const Container = styled.div`
    width: 100px;
    height: 100px;
    background: pink;
    color: white;
`

The above is the detailed content of How to add styles to react components. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn