Component Trong React - Thầy Long Web

Component trong React là bài hướng dẫn cách tạo component, khai báo và dùng tham số cho component trong React, state của component… Để học bài này, bạn cần học bài cơ bản về React để nắm các kiến thức cơ bản trưiớc.

Component trong React

  • Component trong React
  • Function component trong react
    • Ví dụ tạo và sử dụng function component
  • Class component trong react
    • Conponent Constructor
  • Tạo component ở file .js riêng
    • Tạo function component ở file riêng
    • Tạo class component ở file riêng
  • Định nghĩa biến và hàm trong component
  • State trong component
    • State trong class component
    • State trong function component
  • Properties của component
    • Truyền thuộc tính cho component
    • Sử dụng thuộc tính trong component
    • Giá trị mặc định defaultProps của Properties
      • Dùng defaultProps với function component
      • Dùng defaultProps với class component
      • Dùng defaultProps trong JSX
    • Kiểu dữ liệu của tham số
  • Nhúng component vào component cha

Component trong React

Component: là một khối code độc lập, có thể tái sử dụng nhiều lần. Nhờ dùng component, bạn có thể chia UI thành nhiều phần nhỏ, mỗi phần là một component.

Có hai loại component trong react là class và function. Bạn có thể tùy ý sử dụng nhu cầu.

Hai loại component trong React

Trong mỗi component, bạn có thể định nghĩa các biến, các hàm để dùng. Có thể nhúng component vào component cha, nhiều cấp thoải mái. Khi nhúng component có thể truyền thuộc tính cho nó.

Mỗi compoment trong react có state để lưu các trạng thái, dữ liệu để lập trình, có thể truyền state đến các component khác nếu muốn.

Function component trong react

Function component là loại component viết ở dạng function. Có thể viết nhiều component trong 1 file .js hoặc viết riêng mỗi component trong 1 file .js . Trong component function, phải có lệnh return () trả về khối jsx để hiện ra  web. Có thể định nghĩa các biến để dùng trong component nếu cần.

Một khi đã định nghĩa function , bạn có thể sử dụng nó như 1 tag html

Ví dụ tạo và sử dụng function component

//App.jsfunction SanPhamMoi(){ let title="Các sản phẩm mới" return ( <div classname='spmoi'> { title.toUpperCase() } </div> ) }function SanPhamBanChay(){ let title = "Sản phẩm bán chạy" return (<p>{title.toUpperCase()}</p>) }function App() { return ( <div> <SanPhamMoi/> <hr/> <SanPhamBanChay/> </div> );}export default App;

Class component trong react

Để tạo component dạng class, bạn dùng từ khóa class và extends  React.Component. Trong class component phải có hàm render() và lệnh return để xuất dữ liệu jsx. Và cũng như function component, một khi đã định nghĩa class component, bạn có thể dùng nó giống như 1 tag html.

//App.jsimport React from "react";var name ="Laptop Vui";class SanPhamMoi extends React.Component { title = 'Sản phẩm mới'; render(){ return( <div className='spmoi'> {this.title.toUpperCase()} </div> )}}//classclass SanPhamNoiBat extends React.Component { title = 'Sản phẩm nổi bật'; render(){ return( <div className='sphot'> {this.title.toUpperCase()} </div> )}}//classfunction App() { return ( <div> <h4>{name}</h4> <hr/> <SanPhamMoi/> <hr/> <SanPhamNoiBat/> </div> );}export default App;

Conponent Constructor

Nếu trong component dạng class có hàm constructor() thì nó sẽ tự chạy khi gọi component. Trong hàm này bắt buộc phải có lệnh super() hoặc super(props) để chạy constructor của React trước.

class SanPhamNoiBat extends React.Component { title = 'Sản phẩm nổi bật'; constructor(){ super() console.log("Hàm tự động chạy") } render(){ return( <div className='sphot'> <p>{this.title.toUpperCase()} </p> </div> )}}//class

Tạo component ở file .js riêng

Khi tạo component ở file .js riêng, dùng lệnh export trước lệnh định nghĩa component và import nó ở nơi cần dùng.

Tạo function component ở file riêng

//src/top.jsexport function Header(){ return (<header>Laptop Vui</header>)}export function Menu(){ return (<div> <a href="/#">Trang chủ</a> <a href="/#">Sản phẩm</a> </div>)} //src/Footer.jsexport function Footer() { return (<footer>Phát triển 2025 </footer>)} //App.jsimport { Header, Menu } from "./top";import { Footer } from "./Footer";function App() { return ( <div> <Header/> <hr/> <Menu /> <hr/> <Footer/> </div> );}export default App;

Tạo class component ở file riêng

//src/Sach.jsimport React from "react";export class SachMoi extends React.Component { render() { return (<div> <h4 className="title">Sách mới</h4> </div>) }}export class SachQuanTam extends React.Component { render() { return (<div> <h4 className="title">Sách được quan tâm</h4> </div>) }} //classclass Sach extends React.Component { render() { return (<div> <h4>Nói với tuổi 20</h4> <p>120.000 VNĐ </p> </div>) }}//classexport default Sach; //App.jsimport { SachMoi, SachQuanTam } from "./Sach";import Sach from "./Sach";function App() { return ( <div> <SachMoi/> <hr/> <SachQuanTam/> <hr/> <Sach /> </div>)}export default App;

Định nghĩa biến và hàm trong component

Trong component có thể định nghĩa các biến, các hàm để dùng thoải mái

function SanPhamBanChay(){ let title = "Sản phẩm bán chạy" return (<p>{title.toUpperCase()}</p>) }export class SachMoi extends React.Component { title="Sách mới" render() { return (<div> <h4 className="title">{this.title}</h4> </div>) }}

State trong component

State trong class component

Trong class component có sẵn một đối tượng tên là statedùng để lưu các biến dùng trong component. Khi giá trị trong state thay đổi thì component sẽ được render lại (hiện lại nội dung) . Để thay đổi state, bạn dùng hàm this.setState()

Chú ý: nếu dùng constructor(props) super(props) thì code trong hàm constructor mới có thể sử dụng các props theo kiểu this.props được.

//App.jsimport Tong from "./tong";function App() { return (<div> <Tong /> </div> )}export default App; //src/tong.jsimport React from "react";class Tong extends React.Component { constructor(props){ super() this.state = { a:1, b:5 } } tinhtong = ()=> this.state.a + this.state.b; render(){ return( <div className="tong"> <h3>Tổng = {this.tinhtong()} </h3> <button onClick={()=> this.setState( {a:this.state.a+1 })}> Tăng a </button> </div> )}}//classexport default Tong;

State trong function component

Trong function component, muốn dùng state thì bạn import useState vào, rồi khai báo tên của biến trong state và hàm để gán giá trị mới cho nó theo cú pháp const [tênBiến, hàmGánGiaTrị]= useState(giá trị mặc định)

//App.jsimport Tich from "./tich";function App() { return ( <div> <Tich /> </div>) }export default App; //src/tich.jsimport React from "react";import { useState } from "react";function Tich(props ) { const [a, seta] = useState(2); const [b, setb] = useState(3); return( <div className="tich"> <h3>Tích của {a} * {b} = { a*b }</h3> <button onClick={()=> seta(a+1)}>Tăng a</button> <button onClick={()=> setb(b+1)}>Tăng b</button> </div>)}export default Tich;

Properties của component

Các component thường có thuộc tính (props), nhờ thế mà việc sử dụng component rất linh động. Các thuộc tính của component nằm trong đối tượng có tên là props

Truyền thuộc tính cho component

Truyền thuộc tính cho component thì giống như dùng thuộc tính HTML. Mỗi thuộc tính có tên và giá trị , được khai báo lúc cho hiện component

//App.js import Tong from "./tong"; function App() {return ( <div> <Tong a="10" b="15" /> <h3> Trang chủ</h3> </div> )} export default App;

Sử dụng thuộc tính trong component

Bên trong component, để nhận các giá trị từ cha, thì dùng cú pháp props.tên với function component hoặc this.props.tên với class component.

cú pháp dùng props trong component
//src/tong.jsimport React from "react";class Tong extends React.Component {tinhtong =()=> parseInt(this.props.a)+ parseInt(this.props.b)render(){ return( <div className="tong"> Tổng = {this.tinhtong()} </div>)}}//classexport default Tong;

Giá trị mặc định defaultProps của Properties

Để đề phòng trường hợp trong component có dùng props mà bên ngoài không truyền tham số, bạn có thể chỉ định giá trị mặc định cho tham số bằng cách dùng defaultProps ở ngay sau code định nghĩa component (dạng class hoặc funtion ) như sau

class TênComponent extends React.Component {}function TenComponent() {} TênComponent.defaultProps = {tenProp:'giá trị'}

Dùng defaultProps với function component

Sau đây là ví dụ dùng defaultProps với function component

//App.jsimport Tich from "./tich";function App() { return ( <Tich/> ); }export default App; //src/tich.js import React from "react"; const tinhtich = (a, b) => { return a*b; } function Tich(props ) { return( <div className="tich"> Tích của { props.a } * { props.b } là {tinhtich( props.a , props.b )} </div> )} Tich.defaultProps ={ a:2, b:3} export default Tich;

Dùng defaultProps với class component

Sau đây là ví dụ dùng defaultProps với class component

//App.jsimport Tong from "./tong";function App() { return ( <Tong/> );}export default App; //src/tong.js import React from "react"; class Tong extends React.Component { tinhtong=()=>parseInt(this.props.a)+parseInt(this.props.b) render(){ return( <div className="tong">Tổng={this.tinhtong()}</div> )} }//class Tong.defaultProps = { a: 0, b:0 } export default Tong;

Dùng defaultProps trong JSX

Trong JSX, dùng default value thay cho các props không được truyền từ cha theo cú pháp như sau

cách dùng giá trị mặc định của props
//App.js import Tong from "./tong"; function App() { return ( <Tong/> ); } export default App; //src/tong.js import React from "react"; class Tong extends React.Component { tinhtong = ()=> parseInt(this.props.a)+parseInt(this.props.b) render(){ return( <div className="tong"> Tổng {this.props.a || 0 }+{this.props.b || 0 } = {this.tinhtong() || 0 } </div> )} }//class export default Tong;

Kiểu dữ liệu của tham số

Nếu thích bạn có thể chỉ định kiểu dữ liệu của tham số (PropTypes) để code được trực quan hơn, không thích thì thôi không cần thiết lắm

//src/tich.js import React from "react"; import PropsTypes from 'prop-types' const tinhtich = (a, b) => { return a*b; } function Tich(props ) { return( <div className="tich"> Tích của {props.a}*{props.b} là {tinhtich(props.a, props.b)} </div> )} Tich.PropsTypes = { a: PropsTypes.number, b: PropsTypes.number} Tich.defaultProps ={ a:2, b:3} export default Tich;

Nhúng component vào component cha

Có thể nhúng component vào bên trong component khác. Bạn nhúng bao nhiêu cấp cũng được. Khi nhúng component con, nếu nó cần tham số (props) thì nhớ truyền để component con hoạt động đúng. Có thể nhúng nhiều lần component con vào conponent cha cũng được.

//App.js import Tich from "./tich"; function App() {return ( <div> <Tich a="5" b="3" /> <Tich a="2" b="8" /> <Tich a="7" b="2" /> </div> ); } export default App;

Bạn có thể tham khảo thêm về component ở link này:

  • https://www.w3schools.com/react/react_components.asp
  • https://react.dev/reference/react/Component

Từ khóa » Cách Chia Component Trong Reactjs