組件
- 組件的定義
- 使用函數定義一個組件,組件名必須大寫
function HelloMessage(props) {
return <h1>Hello {props.name}!</h1>;
}
- 使用ES6 class定義一個組件
class Welcome extends React.Component {
render() {
return <h1>Hello World!</h1>;
}
}
- 自定義組件
const element = <HelloMessage name="hello" />
- 通過ReactDOM.render() 的方法來將React元素渲染到頁面上:
- 自定義組件中的name屬性通過props.name來獲取
- 在添加屬性時, class 屬性需要寫成 className ,for 屬性需要寫成 htmlFor,這是因爲 class 和 for 是 JavaScript 的保留字。
渲染
- 基本渲染
將變量的值直接顯示在頁面上
function MyCom(props){
let msg = "hello";
return <h3>{msg}</h3>;
}
- 列表渲染
設置key屬性確定唯一標識
<ul>
{
arr.map((item,index)=>{
return <li key={index}>{item}</li>
})
}
</ul>
- 條件渲染
function UserInfo(props){
let {user} = props;
if(user){
return <h2>{user.name} 已登錄</h2>
}
return <h2>請登錄</h2>
}
ReactDOM.render(<UserInfo user={{name:'zhangsan'}}/>,document.getElementById('app'));
組件傳值
傳遞字符串需要將字符串直接作爲屬性值進行傳遞,如果是要傳遞其他數據類型,需要將值放入到{}中進行傳遞
- 傳遞字符串
<MyComponent foo='this is foo' />
=>this is foo - 傳遞數字
<MyComponent foo={1,2,3} />
=>3 - 傳遞布爾類型
<MyComponent foo={true} />
不顯示 - 傳遞數組
<MyComponent foo={[1,2,3,4]} />
=>1234 - 傳遞對象
<MyComponent foo={{name: 'terry' }} />
=>terry
類組件
可以通過ES6中的類來創建組件,該類繼承React.Component,並且擁有一個render()函數
render函數表示渲染,每次重新渲染都要調用該函數
class Welcome extends React.Component {
render() {
return <h1>Hello World!{this.props.name}</h1>;
}
}
Fragment
Fragment 允許將子列表分組,而無需向 DOM 添加額外節點。
return (
<React.Fragment>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
</React.Fragment>
);