一、 一些零散的基礎概念
1. 組件 Components
組件可以被描述爲用戶界面的一部分。它們可以被重複使用,也可以被嵌套在其它組件中。
2. 組件類型 Component Types
1)無狀態的功能性組件 Stateless Functional Component
Properties ---------> JavaScript Function ---------> HTML (JSX)
(props)
2)狀態性的類組件 Stateful Class Component
Properties ---------> ES6 class ---------> HTML (JSX)
(props)
3)功能性組件與類組件的優劣
Functional Class
Simple functions More feature rich
Use Function components as much as possible Maintain their own private date - state
Absence of 'this' keyword Complex UI logic
Solution without using state Provide lifecycle hooks
Mainly responsible for the UI Stateful / Smart / Container
Stateless / Dumb / Presentational
4) 舉例
無狀態的功能性組件例子:
- JavaScript Functions
如:function greeting(props) {
return <h1>Hello, { props.name }</h1>;
}
狀態性的類組件例子:
- 類擴展組件類,渲染方法返回HTML
如:class greeting extends React.Component {
render() {
return <h1>Hello, { this.props.name }</h1>;
}
}
3. 導出文件中的函數 export function
1)使用default關鍵詞
如:export default Greet
在導入時,default允許使用自定義名字
如:import myName from ‘./components/Greet’
4. JSX
- JavaScript XML(JSX)- Extension to the JavaScript language syntax.
- Write XML - like code for elements and components.
- JSX tags have a tag name, attributues, and children.
- 寫React 應用 并不是必須使用JSX,但,使用了JSX的話,可以使react的代碼看上去簡單、乾净。
- JSX最终会转译成浏览器能够理解的纯JavaScript。