hoc-lap-trinh-9

1. Cài đặt môi trường React

Trước tiên, bạn cần cài đặt Node.js và npm (Node Package Manager) trên máy tính của bạn. Sau đó, bạn có thể tạo một dự án React mới bằng cách sử dụng Create React App, một công cụ do đội ngũ React phát triển để giúp bạn thiết lập nhanh chóng một dự án React.

Cài đặt Create React App:

npx create-react-app my-app

cd my-app

npm start

2. Cấu trúc dự án React

Sau khi tạo dự án, bạn sẽ thấy cấu trúc thư mục như sau:

my-app

├── node_modules

├── public

│   ├── index.html

│   └── ...

├── src

│   ├── App.css

│   ├── App.js

│   ├── App.test.js

│   ├── index.css

│   ├── index.js

│   ├── logo.svg

│   └── ...

├── package.json

└── ...
  • public: Chứa các tài nguyên tĩnh như HTML, hình ảnh, v.v.
  • src: Chứa các file mã nguồn của ứng dụng React.

3. JSX (JavaScript XML)

JSX là cú pháp mở rộng cho JavaScript, cho phép bạn viết code giống HTML bên trong JavaScript.

Ví dụ:

const element = <h1>Hello, world!</h1>;

4. Components (Thành phần)

React là một thư viện dựa trên thành phần. Một thành phần trong React có thể là một function component hoặc class component.

Function Component:

function Welcome(props) {

  return <h1>Hello, {props.name}</h1>;

}

Class Component:

class Welcome extends React.Component {

  render() {

    return <h1>Hello, {this.props.name}</h1>;

  }

}

5. Props (Properties)

Props là các tham số được truyền vào component để tùy biến và hiển thị dữ liệu.

Ví dụ:

function Welcome(props) {

  return <h1>Hello, {props.name}</h1>;

}
function App() {

  return (

    <div>

      <Welcome name="Sara" />

      <Welcome name="Cahal" />

      <Welcome name="Edite" />

    </div>

  );

}

6. State (Trạng thái)

State là một đối tượng đặc biệt trong React, được sử dụng để lưu trữ dữ liệu hoặc thông tin về component.

Class Component với State:

class Clock extends React.Component {

  constructor(props) {

    super(props);

    this.state = {date: new Date()};

  }

  componentDidMount() {

    this.timerID = setInterval(

      () => this.tick(),

      1000

    );

  }

  componentWillUnmount() {

    clearInterval(this.timerID);

  }

  tick() {

    this.setState({

      date: new Date()

    });

  }

  render() {

    return (

      <div>

        <h1>Hello, world!</h1>

        <h2>It is {this.state.date.toLocaleTimeString()}.</h2>

      </div>

    );

  }

}

7. Event Handling (Xử lý sự kiện)

React cho phép bạn xử lý các sự kiện như click, submit, etc.

Ví dụ:

class Toggle extends React.Component {

  constructor(props) {

    super(props);

    this.state = {isToggleOn: true};

    // This binding is necessary to make `this` work in the callback

    this.handleClick = this.handleClick.bind(this);

  }

  handleClick() {

    this.setState(state => ({

      isToggleOn: !state.isToggleOn

    }));

  }

  render() {

    return (

      <button onClick={this.handleClick}>

        {this.state.isToggleOn ? 'ON' : 'OFF'}

      </button>

    );

  }

}

8. React Hooks

Hooks là một tính năng mới trong React 16.8, cho phép bạn sử dụng state và các tính năng khác của React mà không cần viết class component.

useState Hook:

import React, { useState } from 'react';

function Counter() {

  const [count, setCount] = useState(0);

  return (

    <div>

      <p>You clicked {count} times</p>

      <button onClick={() => setCount(count + 1)}>

        Click me

      </button>

    </div>

  );

}

9. Conditional Rendering (Render điều kiện)

React cho phép bạn render các thành phần dựa trên điều kiện.

Ví dụ:

function Greeting(props) {

  const isLoggedIn = props.isLoggedIn;

  if (isLoggedIn) {

    return <h1>Welcome back!</h1>;

  }

  return <h1>Please sign up.</h1>;

}

10. Lists and Keys (Danh sách và khóa)

Khi render một danh sách các phần tử, bạn cần cung cấp một “key” để React có thể theo dõi từng phần tử một cách hiệu quả.

Ví dụ:

function NumberList(props) {

  const numbers = props.numbers;

  const listItems = numbers.map((number) =>

    <li key={number.toString()}>

      {number}

    </li>

  );

  return (

    <ul>{listItems}</ul>

  );

}

11. Form Handling (Xử lý biểu mẫu)

React xử lý các biểu mẫu bằng cách kiểm soát giá trị của các input thông qua state.

Ví dụ:

class NameForm extends React.Component {

  constructor(props) {

    super(props);

    this.state = {value: ''};

    this.handleChange = this.handleChange.bind(this);

    this.handleSubmit = this.handleSubmit.bind(this);

  }

  handleChange(event) {

    this.setState({value: event.target.value});

  }

  handleSubmit(event) {

    alert('A name was submitted: ' + this.state.value);

    event.preventDefault();

  }

  render() {

    return (

      <form onSubmit={this.handleSubmit}>

        <label>

          Name:

          <input type="text" value={this.state.value} onChange={this.handleChange} />

        </label>

        <input type="submit" value="Submit" />

      </form>

    );

  }

}

12. Lifting State Up (Nâng trạng thái lên)

Khi nhiều component cần dùng chung một dữ liệu, bạn có thể nâng trạng thái lên parent component.

Ví dụ:

function BoilingVerdict(props) {

  if (props.celsius >= 100) {

    return <p>The water would boil.</p>;

  }

  return <p>The water would not boil.</p>;

}
class Calculator extends React.Component {

  constructor(props) {

    super(props);

    this.state = {temperature: ''};

    this.handleChange = this.handleChange.bind(this);

  }

  handleChange(e) {

    this.setState({temperature: e.target.value});

  }

  render() {

    const temperature = this.state.temperature;

    return (

      <fieldset>

        <legend>Enter temperature in Celsius:</legend>

        <input

          value={temperature}

          onChange={this.handleChange} />

        <BoilingVerdict

          celsius={parseFloat(temperature)} />

      </fieldset>

    );

  }

}

Đây là những kiến thức cơ bản về React mà bạn cần nắm vững để bắt đầu xây dựng các ứng dụng web phức tạp hơn. Hãy thực hành nhiều ví dụ và đọc tài liệu chính thức của React để hiểu sâu hơn và nâng cao kỹ năng lập trình của mình.

By hoadv