/
ReactJS - Component

ReactJS - Component

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> </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()

import React from 'react'; import ReactDOM from 'react-dom'; import App from './App.jsx'; ReactDOM.render(<App />, document.getElementById('root'));

Và kết quả ta được:

react_components_stateless

STATEFULL 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":1, "name":"Foo", "age":"20" }, { "id":2, "name":"Bar", "age":"30" }, { "id":3, "name":"Baz", "age":"40" } ] }; } render() { return ( <div> <Header/> <table> <tbody> { this.state.data.map((person, i) => <TableRow key = {i} data = {person} />) } </tbody> </table> </div> ); } } class Header extends React.Component { render() { return ( <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ư sau:

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.

react_components_statefull

Related content

ReactJS - State - Props
ReactJS - State - Props
More like this
ReactJS - JSX
More like this
ReactJS - Tìm hiểu Events trong React
ReactJS - Tìm hiểu Events trong React
More like this
ReactJS - Component Life Cycle
ReactJS - Component Life Cycle
More like this
ReactJS - Refs
ReactJS - Refs
More like this
Simple POS (Client)
Simple POS (Client)
Read with this