Bài 3: ReactJS Tìm hiểu các Components trong React Trong bài này chúng ta sẽ tìm hiểu về các components trong React và cách quản lý chúng. STATELESS EXAMPLE Chúng ta tiếp tục sử dụng lại App.js, thêm vào 2 components đó là Header và Content, App sẽ chứa 2 component mới thêm vào, sau đó ta export thằng App. App.js
Trang 1Bài 3: ReactJS - Tìm hiểu các
Components trong React
Trong bài này chúng ta sẽ tìm hiểu về các components trong React và cách quản lý chúng
STATELESS EXAMPLE
Chúng ta tiếp tục sử dụng lại App.js, thêm vào 2 components đó là Header và Content, App sẽ chứa 2 component mới thêm vào, sau đó ta export thằng App
App.js
import React from 'react' ;
class App extends React Component
render ()
return
<div>
< Header />
< Content />
</ div >
);
}
}
class Header extends React Component
render ()
return
<div>
<h1> Header </ h1 >
Trang 2</ div >
);
}
}
class Content extends React Component
render ()
return
<div>
<h2> Content </ h2 >
<p> The content text !!!</ p
</ div >
);
}
}
export default App;
Để render App chúng ta cần import nó vào index.js và gọi hàm reactDom.render() như
đã làm ở bài 1: Enviroment Setup
import React from 'react' ;
import ReactDOM from 'react-dom' ;
import App from './App.jsx' ;
ReactDOM render (< App />, document getElementById ( 'app' ));
Và kết quả ta được:
Trang 3STATEFULL EXAMPLE
Trong ví dụ này chúng ta sẽ thêm state vào trong App component, state sẽ là 1 mảng object, chúng ta thay content thành TableRow component, TableRow sẽ nhận các giá trị state của component cha là App (Chúng ta sẽ tìm hiểu kĩ hơn về state và props ở các bài sau)
App.js
import React from 'react' ;
class App extends React Component
constructor ()
super ();
this state = {
data :
[
{
"id" : ,
"name" : "Foo" ,
"age" : "20"
},
{
"id" : ,
Trang 4"name" : "Bar" ,
"age" : "30"
},
{
"id" : ,
"name" : "Baz" ,
"age" : "40"
}
]
}
}
render ()
return
<div>
< Header />
<table>
<tbody>
{ this state data map (( person , i ) => TableRow key = { }
data = { person } />)}
</ tbody >
</ table >
</ div >
);
}
}
class Header extends React Component
render ()
Trang 5return
<div>
<h1> Header </ h1 >
</ div >
);
}
}
class TableRow extends React Component
render ()
return
<tr>
<td> { this props data id }</ td >
<td> { this props data name }</ td >
<td> { this props data age }</ td >
</ tr >
);
}
}
export default App ;
Hàm map giống như for-loop js, nếu viết bằng for thì sẽ như giầy:
for (let i = 0; i < this.state.data.length; i++) {
<TableRow key = {i}
data = {this.state.data[i]} />
}
key={i} giúp React update lại element 1 cách chính xác với key đó thay vì render lại toàn bộ list, khi ta thay đổi 1 thành phần nào đó trong state, việc này rất hiệu quả nếu chúng ta có viết các ứng dụng lớn nhiều elements sau này
Index.js ta giữ nguyên code,
import React from 'react' ;
Trang 6import ReactDOM from 'react-dom' ;
import App from './App.jsx' ;
ReactDOM render (< App />, document getElementById ( 'app' ));
Kết thúc bài 3 ở đây, các bạn xem lại r thực hành nha