0
0
Lập trình
Flame Kris
Flame Krisbacodekiller

Hướng Dẫn Tạo Lịch Sử Dụng ReactJS và TypeScript với Moment.js

Đăng vào 2 tuần trước

• 6 phút đọc

Giới Thiệu

Bài viết này sẽ hướng dẫn bạn cách tạo một ứng dụng lịch đơn giản bằng ReactJS và TypeScript, kết hợp với thư viện Moment.js để xử lý ngày tháng. Chúng ta sẽ xây dựng các chức năng cơ bản như hiển thị ngày tháng trong tháng hiện tại, ngày tháng trước và sau đó.

Nội Dung

  1. Tạo Context API để Chia Sẻ Dữ Liệu
    Để quản lý trạng thái và chia sẻ giữa các component, chúng ta sẽ tạo một Context API. Đây là cách dùng Context API trong dự án của chúng ta:

    javascript Copy
    'use client';
    import { PropsWithChildren, createContext, useContext } from 'react';
    import useLogic from './hook';
    
    type Extra = {};
    
    type ValueCtx = ReturnType<typeof useLogic> & Extra;
    
    export const CalendarCtx = createContext({} as ValueCtx);
    
    export const CalendarProvider = ({ ...props }: PropsWithChildren<Extra>) => {
        const valueCtx = useLogic();
        return (
            <CalendarCtx.Provider value={{ ...valueCtx, ...props }}>
                <>{props.children}</>
            </CalendarCtx.Provider>
        );
    };
    
    export const useCalendarCtx = () => useContext(CalendarCtx);
  2. Tạo Hook Để Xử Lý Logic
    Hook này sẽ chứa các hàm để điều khiển logic liên quan đến lịch:

    javascript Copy
    'use client';
    import moment from 'moment';
    import { useState } from 'react';
    import { calcDays, dataDate } from './data';
    import { onSolar2Lunar } from './lunar';
    
    const useLogic = () => {
        const [date, setDate] = useState(moment());
    
        const handleReload = () => setDate(moment());
        const handlePrev = () => setDate((element) => moment(element).subtract(1, 'month'));
        const handleNext = () => setDate((element) => moment(element).add(1, 'month'));
    
        const currentLunar = () => {
            const curdate = dataDate({ date: moment() });
            return onSolar2Lunar(curdate.day, curdate.curMonth, curdate.year);
        };
    
        return {
            date,
            setDate,
            listDay: calcDays({ ...dataDate({ date }) }),
            current: dataDate({ date }),
            handlePrev,
            handleNext,
            handleReload,
            currentLunar,
        };
    };
    
    export default useLogic;
  3. Phương Thức Xử Lý Ngày Tháng
    Chúng ta cần một phương thức để xử lý ngày tháng cho lịch hai chiều. Phương thức dưới đây sẽ cho phép bạn lấy thông tin chi tiết về các ngày trong tháng:

    javascript Copy
    import { range } from 'lodash';
    import moment, { Moment } from 'moment';
    import 'moment/locale/vi';
    import { onSolar2Lunar } from './lunar';
    import { CalcDays, ItemDay } from './types';
    
    // Định nghĩa ngày
    enum DefineDays {
        DaysOut = 'DaysOut',
        DaysIn = 'DaysIn',
    }
    
    export type DataDate = { date: Moment };
    
    export const dataDate = ({ date }: DataDate) => {
        const day = date.date();
        const year = date.year();
        const month = date.month();
        const daysInMonth = date.daysInMonth();
        // Các tính toán ngày khác được thực hiện ở đây.
        // 
        return {
            day,
            year,
            month,
            curMonth: month + 1,
            daysInMonth,
            // Cũng định nghĩa các thuộc tính khác như tuần cũ, tuần mới...
        };
    };
    
    export const calcDays = ({ /* Tham số */ }) => {
        // Logic xử lý và trả về danh sách các ngày trong tháng
    };
  4. Định Nghĩa Dữ Liệu
    Chúng ta cũng cần xác định các loại dữ liệu cho ngày tháng trong ứng dụng:

    javascript Copy
    import { Moment } from 'moment';
    
    export type CalcDays = {
        // Định nghĩa các tham số cho tính toán ngày
    };
    
    export type ItemDay = {
        daysLunar: LunarType;
        days: number;
        type: string;
        isToday?: boolean;
        daysSolar?: DaySolarType;
    };
    
    export interface LunarType {
        dd: number;
        mm: any;
        yy: number;
        ix: any;
        LLLL: string;
        DM: string;
    }
    
    export type DaySolarType = {
        day: number;
        month: number;
        year: number;
        ddmm?: string;
        ddmmyyyy?: string;
    };
  5. Tính Toán Lịch Âm
    Cuối cùng, chúng ta sẽ tính toán lịch âm dựa trên các hàm đã tạo:

    javascript Copy
    // Tính toán chuyển đổi giữa lịch âm và lịch dương
    export const onSolar2Lunar = (D = 0, M = 0, Y = 0) => {
        // Logic chuyển đổi
    };

Kết Luận

Bài viết này đã hướng dẫn bạn từng bước để xây dựng một ứng dụng lịch cơ bản với ReactJS và TypeScript. Hy vọng bạn sẽ áp dụng thành công trong dự án của mình!
source: viblo

Gợi ý câu hỏi phỏng vấn
Không có dữ liệu

Không có dữ liệu

Bài viết được đề xuất
Bài viết cùng tác giả

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào