Created
May 20, 2019 09:30
-
-
Save Rainbowrain-TW/8d88e41e9fb75dc87368e5e05644d2e0 to your computer and use it in GitHub Desktop.
basiclyReactComponent
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//引入 React 及 Component | |
import React, {Component} from 'react' | |
//建立一個名為 App 的類別並繼承 Component | |
class App extends Component{ | |
//初始化結構,學過其他程式的話可以當作建構子 | |
constructor(props){ | |
super(props) //super() 繼承父類別的結構,類似java中的super()或C#中的base() | |
this.state = { //設定在 App 這個類別中要使用的 state | |
count: 1 //跟寫 js 的 object一樣方法 | |
} | |
this.addCount = this.addCount.bind(this) | |
//將 addCount 這個函式的 this 綁定為 App 初始化的 instance | |
//主要目的是要取得 state 及 props | |
//props是用來取得父類別或父元件的結構資訊 | |
//假設我在 App 這個類別裡面又建立了一個類別叫 Title | |
//那Title的 super(props) 指的就是 App 這個 instance | |
//要搞清楚 props 可能還要一點經驗,但重點概念: props即是指向 父層、上層或外層 | |
} | |
//添加事件或函式的方法 | |
addCount(){ | |
this.setState({ //透過setState來改變 App.state 中的資料,所以要在 construct 中綁定 | |
count:this.state.count + 1 //不能用 this.state.count++ | |
}) | |
} | |
//render()是 component 最重要的 function,用來決定畫面的呈現 | |
//一個 component class 中只要有 render() 存在就可以執行大多數的行為 | |
//沒有 render() 的話就會報錯 | |
//render() return 的內容當中最外層元素只能有一個 | |
render(){ // | |
let text = 'pink text' //可以在 render() 建立一些變數 | |
let rdn = Math.floor(Math.random() * 100) //可以呼叫 javascript 的function | |
let oddeven = (rdn % 2 === 0) ? 'even' : 'odd' //三元運算子之類的運算式也可以使用 | |
let style_h3 = {color:'pink'} //建立物件準備當 CSS 的參數 | |
return ( //return 的內容,在 return 中寫註解要用 {} 包著 | |
<div> {/*最外層元素,裡面可以包多個(層)的 HTML Element 或其他 Component */} | |
<button onClick={this.addCount}> + 1 </button> | |
<div>{this.state.count}</div> | |
<h3 style={style_h3}>{oddeven}</h3> | |
<h3 style={style_h3}>{text}</h3> | |
</div> | |
) | |
} | |
/* 禁止項目, 這些方式寫在在 React 是不行的 | |
function Hello(){ | |
console.log('Hello') | |
} | |
Const sayHello = function(){ | |
console.log('Hello') | |
} | |
var text = 'hello' | |
*/ | |
} | |
//匯出寫好的 App | |
export default App |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment