在上一篇CRA文章中,大概講解一下各個目錄說明,這篇要來講src目錄裡的兩個檔案
/src/index.js

<APP />是一個寫好的component(組件),第4行的import App from ‘./App’為引入這個組件,也可以將<App />替換成<h1>TEST</h1>,但要注意的是只能有一個根節點,如果說寫成 <h1>TEST</h1><span>SUPER</span>這樣是不允許的,而後方語法則是會渲染到網頁上id為root的DOM元素,而這個root就寫在/public/index.html Functional Component 與 Class Component component就像是JavaScript的function,它接收任意的參數(稱為props)並且回傳描述畫面的React element,也可使用Class定義component,以往在使用class時擁有額外特性,當需要管理到state或lifecycle就需要使用class component,但現在有了Hooks API管理就方便許多,幾乎可以都使用functional component,之後會再說明。
現在來做點簡單的修改,使用Function定義組件
function Clock(props) {
return (
<div>
<h1>現在時間</h1> <strong>{props.time.toLocaleTimeString()}</strong>
</div>
)
}
//或是,使用Class定義組件
class Clock extends React.Component {
render() {
return (
<div>
<h1>realTime</h1>
<strong>{this.props.time.toLocaleTimeString()}</strong>
</div>
)
}
}
var runtime = () => { ReactDOM.render(<Clock time={new Date()} />, document.getElementById('root')) } setInterval(rc, 1000)
註:this.props.time >> this是這個元件類別所產生的物件實體,props表示屬性,屬性可以有多個,就跟HTML的屬性一樣(<img src="images/test.jpg" style={{width="50″ height="50″}} />)。
/src/App.js

上圖是用function的方式寫component,也可以改成箭頭函式
const App = () => {
return (
<h1>TEST<h1>
)
}
在寫component時可以用class或是function方式去建構,組件的成立可分為三個部分
- 引入套件和檔案
- 組件內容
- 將組件export供其它JS檔使用組件