css寫法從以前塞在html裡到引用外部檔案,後來演進變數與模組化。這裡簡單介紹react裡使用css的方法,使用細節可能3~5篇還寫不完,搭配工具使用可能又是一個無底洞。react使用css方法這裡介紹3種,第4種模組化需搭配webpack暫不說明。css這麼寫是一大學問,尤其是專案一大每次尋找某種樣式就像大海撈針一樣。
styled-components(使用前記得安裝與import)
npm install styled-components --save
參考資料
https://github.com/styled-components/styled-components
src/CssStyleTest.js
import React, { Component } from 'react';
import './CssStyleBox.css';
import styled from 'styled-components';
class CssStyleTest extends React.Component {
constructor(props) {
super(props);
}
render() {
return <div>
<CssStyleBox />
<InlineBox />
<StyledComponentBox />
</div>
}
}
//css style
const CssStyleBox = () => (
<div className="CssStyleBox">
<p className="CssStyleBox_content">CSS style box</p>
</div>
);
//inline style
const divStyle = {
margin: '40px',
border: '5px solid green'
};
const pStyle = {
fontSize: '15px',
textAlign: 'center'
};
const InlineBox = () => (
<div style={divStyle}>
<p style={pStyle}>Inline style box</p>
</div>
);
//styled-components
const Div = styled.div`
margin: 40px;
border: 5px double blue;
`;
const Paragraph = styled.p`
font-size: 15px;
text-align: center;
`;
const StyledComponentBox = () => (
<Div>
<Paragraph>styled-components box</Paragraph>
</Div>
);
export default CssStyleTest;
src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import CssStyleTest from './CssStyleTest';
import registerServiceWorker from './registerServiceWorker';
ReactDOM.render(<CssStyleTest />, document.getElementById('root'));
registerServiceWorker();
輸出畫面