給Header.jsHeader.js增長樣式javascript
駝峯命名法css
js 寫 css 樣式使用原始屬性須要雙引號括起來。html
注意:const 定義要放在 render 裏面return 函數以前,不然會報錯。java
import React from 'react'; import ReactDOM from 'react-dom'; //export 暴露 export default class ComponentHeader extends React.Component{ render(){ //解析類的輸出 const styleComponentHeader = { header: { backgroundColor: "#333", color: "#fff", "padding-top": "15px", //css原生 不推動 paddingBottom: "15px" }, //定義其餘樣式 }; return ( <header style = {styleComponentHeader.header}> <h1>這裏是頭部</h1> </header> ) } }
.smallFountSize h1{ font-size: 12px; }
<head> <link rel="stylesheet" href="./src/css/style.css"/> </head> <div id="example">123dfdf</div> <script type="text/javascript" src="/src/bundle.js"></script>
import React from 'react'; import ReactDOM from 'react-dom'; //export 暴露 export default class ComponentHeader extends React.Component{ render(){ //解析類的輸出 const styleComponentHeader = { header: { backgroundColor: "#333", color: "#fff", "padding-top": "15px", //css原生 不推動 paddingBottom: "15px" }, //定義其餘樣式 }; return ( <header style={styleComponentHeader.header} className="smallFountSize"> <h1>這裏是頭部</h1> </header> ) } }
點擊 header 改變。react
1.存儲樣式,state --> 建立構造函數,存儲 true false 值,點擊改變,利用值來控制樣式dom
2. "padding-top": {this.state.miniHeader}?"3px" : "15px", 函數
3. state 與 css 融合,引發樣式及時變化this
import React from 'react'; import ReactDOM from 'react-dom'; //export 暴露 export default class ComponentHeader extends React.Component{ constructor(){ super(); this.state = { miniHeader: false, } } switchHeader(){ this.setState({ miniHeader: !this.state.miniHeader, }) } render(){ //解析類的輸出 const styleComponentHeader = { header: { backgroundColor: "#333", color: "#fff", "padding-top": (this.state.miniHeader) ? "3px" : "15px", //css原生 不推薦 paddingBottom: (this.state.miniHeader)? "3px" : "15px", }, //定義其餘樣式 }; return ( <header style={styleComponentHeader.header} className="smallFountSize" onClick={this.switchHeader.bind(this)}> <h1>這裏是頭部</h1> </header> ) } }