Home > Article > Web Front-end > How to write style in react
How to write style in react: 1. Use inline style; 2. Use className method; 3. Use classnames to dynamically modify the style; 4. Use the [styled-components] plug-in to write label styles.
The operating environment of this tutorial: windows7 system, React17 version. This method is suitable for all brands of computers.
How to write style in react:
1. Inline
import React, { Fragment } from "react"; class Style extends React.Component { constructor(props) { super(props); } render() { const txtColor = { color: '#F00' } return ( <Fragment> <h1 style={txtColor}></h1> </Fragment> ); } } export default Style;
This writing method is not recommended, style If there are too many, the code will be messy!
2. Use className
import React, { Fragment } from "react"; import "./../../style.css"; class Style extends React.Component { constructor(props) { super(props); } render() { return ( <Fragment> <h1 className="textColor"></h1> </Fragment> ); } } export default Style;
to create a new .css
file and import the file. If you use className="textColor"
in the tag, you can use the style with the class 'textColor' in the imported .css file. This method is sufficient for general projects.
3. Use classnames to dynamically modify the style
import React, { Fragment } from "react"; import classNames from 'classnames' class Style extends React.Component { constructor(props) { super(props); } render() { return ( <Fragment> <h1 className={classNames('textColor', {'textContent': false} ,{'textTitle': true})}></h1> </Fragment> ); } } export default Style;
This method of dynamically modifying the style requires installing the plug-in classnames. In the above code, the classes of the h1 tag include textColor and textTitle. This is generally the case in projects. Use.
4. Use the styled-components plug-in to write the label style.
import React, { Fragment } from 'react' import styled from 'styled-components' const Title = styled.h1` color: #f00; ` class Style extends React.Component { constructor(props) { super(props) } render() { return ( <Fragment> <Title>复习style</Title> </Fragment> ) } } export default Style
Use styled-components
to write the label style. You need to install it first. Plug-in. The above code defines a Title, sets the style for the h1 tag through styled, and then the Title used in the component is equivalent to the styled h1 tag. This method is more common in large projects.
Related free learning recommendations: javascript(Video)
The above is the detailed content of How to write style in react. For more information, please follow other related articles on the PHP Chinese website!