react寫style的方法:1、使用內(nèi)聯(lián)式;2、使用className方法;3、使用classnames動(dòng)態(tài)修改樣式;4、使用【styled-components】插件寫標(biāo)簽樣式。
本教程操作環(huán)境:windows7系統(tǒng)、React17版,該方法適用于所有品牌電腦。
react寫style的方法:
1、內(nèi)聯(lián)式
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;
這種寫法不推薦使用,樣式多了之后,會(huì)導(dǎo)致代碼比較亂!
2、使用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;
新建一個(gè).css
文件,將文件引進(jìn)來,標(biāo)簽中使用className=“textColor”
,就可以使用引入.css文件中類為’textColor’的樣式了.一般的項(xiàng)目用這個(gè)方式就可以了.
3、使用classnames動(dòng)態(tài)修改樣式
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;
這種動(dòng)態(tài)修改樣式的方式,需要安裝插件classnames.上面的代碼中,h1標(biāo)簽的類有textColor和textTitle.項(xiàng)目中一般也會(huì)使用.
4、使用styled-components插件寫標(biāo)簽樣式
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>復(fù)習(xí)style</Title> </Fragment> ) } } export default Style
使用styled-components
給標(biāo)簽寫樣式,首先需要安裝該插件.上面的代碼是定義一個(gè)Title,通過styled給h1標(biāo)簽設(shè)置樣式,然后在組件中使用的Title就相當(dāng)于寫過樣式的h1標(biāo)簽.這種方式在大項(xiàng)目中比較常見.
相關(guān)免費(fèi)學(xué)習(xí)推薦:javascript(視頻)