1.React 不強制要求使用 JSX,但是大多數人發現,在 JavaScript 代碼中將 JSX 和 UI 放在一起時,會在視覺上有輔助作用。它還可以使 React 顯示更多有用的錯誤和警告消息。
2.建議將內容包裹在括號中,雖然這樣做不是強制要求的,但是這可以避免遇到自動插入分號陷阱。
const element = <p>{formatName(user)};
組件:
- 函數組件
/*該函數是一個有效的 React 組件,因爲它接收唯一帶有數據的 “props”(代表屬性)
對象與並返回一個 React 元素。這類組件被稱爲“函數組件”, 因爲它本質上就是
JavaScript 函數。*/
function Welcome(props){
return <h1>hello,{props.name}</h1>
}
- class組件
//與上邊函數組件等效
class Welcome extends React.Component{
render(){
return <h1>hello,{this.props.name}</h1>
}
}
- 渲染組件
//html部分
<div id="root"></div>
//js部分
function Welcome(props){
return <h1>hello,{props.name}</h1>
}
const element = <Welcome name="Sara" />>
ReactDOM.render(
element,
document.getElementById('root')
)
注意: 組件名稱必須以大寫字母開頭。
React 會將以小寫字母開頭的組件視爲原生 DOM 標籤。例如,< div/ >代表 HTML 的 div 標籤,而 < Welcome / > 則代表一個組件,並且需在作用域內使用 Welcome。
- 組合組件
//html部分
<div id="root"></div>
//js部分
function Welcome(props){
return <h1>hello,{props.name}</h1>
}
function App(){
return {
<div>
<Welcome name="Sara" />
<Welcome name="Cahal" />
<Welcome name="Edite" />
</div>
}
}
ReateDOM.render(
<App/>>,
document.getElementById('root')
)
- 提取組件