首頁  >  文章  >  web前端  >  react怎麼寫style

react怎麼寫style

coldplay.xixi
coldplay.xixi原創
2020-11-27 16:32:2212117瀏覽

react寫入style的方法:1、使用內聯式;2、使用className方法;3、使用classnames動態修改樣式;4、使用【styled-components】外掛程式寫標籤樣式。

react怎麼寫style

本教學操作環境:windows7系統、React17版,此方法適用於所有品牌電腦。

react寫入style的方法:

1、內聯式

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;

這種寫法不建議使用,樣式多了之後,會導致程式碼比較亂!

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;

新建一個.css檔案,將檔案引進,標籤中使用className=“textColor”,就可以使用引入.css檔案中類別為'textColor'的樣式了.一般的項目用這個方式就可以了.

#3、使用classnames動態修改樣式

import React, { Fragment } from "react";
import classNames from &#39;classnames&#39;
class Style extends React.Component {
  constructor(props) {
    super(props);
  }
  render() {
    return (
     <Fragment>
         <h1 className={classNames(&#39;textColor&#39;, {&#39;textContent&#39;: false} ,{&#39;textTitle&#39;: true})}></h1>
     </Fragment>
    );
  }
}
export default Style;

這種動態修改樣式的方式,需要安裝插件classnames.上面的程式碼中,h1標籤的類別有textColor和textTitle.專案中一般也會使用.

4、使用styled-components外掛程式寫標籤樣式

import React, { Fragment } from &#39;react&#39;
import styled from &#39;styled-components&#39;
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

使用styled-components給標籤寫樣式,首先需要安裝該外掛.上面的程式碼是定義一個Title,透過styled為h1標籤設定樣式,然後在元件中使用的Title就相當於寫過樣式的h1標籤.這種方式在大專案中比較常見.

相關免費學習推薦:javascript#(影片)

以上是react怎麼寫style的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn