Home Web Front-end JS Tutorial Detailed explanation of how to develop calendar components using react

Detailed explanation of how to develop calendar components using react

Sep 06, 2018 pm 04:53 PM
css javascript react.js webpack calendar

本篇文章给大家带来的内容是关于php中如何得到小程序传来的json数组数据(代码),有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。

准备工作

提前需要准备好react脚手架开发环境,由于react已经不支持在页面内部通过jsx.transform来转义,我们就自己大了个简易的开发环境

创建一个文件夹,命名为react-canlendar

cd ./react-canlendar
Copy after login

运行

npm init
Copy after login

一路enter我们得到一个package.json的文件

安装几个我们需要的脚手架依赖包

npm install awesome-typescript-loader typescript webpack webpack-cli -D
Copy after login

安装几个我们需要的类库

npm install @types/react react react-dom --save
Copy after login

基础类库安装完毕,开始构建webpack配置

新建一个目录config,config下面新增一个文件,名字叫做webpack.js

var path = require('path')

module.exports = {
    entry: {
        main: path.resolve(__dirname, '../src/index.tsx')
    },
    output: {
        filename: '[name].js'
    },
    resolve: {
        extensions: [".ts", ".tsx", ".js", ".json"]
    },
    module: {
        rules: [
            {test: /\.tsx?$/, use: ['awesome-typescript-loader']}
        ]
    }
}
Copy after login

还需要创建一个index.html文件,这是我们的入口文件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    <p id="root"></p>
    <script src="./dist/main.js"></script>
</body>
</html>
Copy after login

以上环境只是一个极简单的环境,真实环境要比这个复杂的多

好了,言归正传,我们还是聚焦到日历组件的开发中来吧

创建一个src文件夹,内部创建一个index.tsx文件。

这个入口文件很简单就是一个挂载

import * as React from 'react'
import * as ReactDOM from 'react-dom'

ReactDOM.render((
  <p>
    test
  </p>
), document.getElementById('root'))
Copy after login

ok,打开页面可以看到页面正常显示了test字样。

我们需要创建Calendar组件了。

创建一个components文件夹,内部创建一个Calendar.tsx文件。

import * as React from 'react'

export default class Calendar extends React.Component {
  render() {
   
    return (<p>
        日历
    </p>)
  }
}
Copy after login

在index.tsx中把Calendar.tsx引入,并使用起来。于是index.tsx变成这个样子。

import * as React from 'react'
import * as ReactDOM from 'react-dom'
import Calendar from './components/Calendar'

ReactDOM.render((
  <p>
    <Calendar/>
  </p>
), document.getElementById('root'))
Copy after login

可以看到页面显示了日历字样。

要显示日历,首先需要显示日历这个大框以及内部的一个个小框。实现这种布局最简单的布局就是table了

所以我们首先创建的是这种日历table小框框,以及表头的星期排列。

import * as React from 'react'

const WEEK_NAMES = ['日', '一', '二', '三', '四', '五', '六']
const LINES = [1,2,3,4,5,6]

export default class Calendar extends React.Component {
  render() {
    return (<p>
      <table cellPadding={0} cellSpacing={0} className="table">
        <thead>
        <tr>
          {
            WEEK_NAMES.map((week, key) => {
              return <td key={key}>{week}</td>
            })
          }
        </tr>
        </thead>
        <tbody>
        {
          LINES.map((l, key) => {
            return <tr key={key}>
              {
                WEEK_NAMES.map((week, index) => {
                  return <td key={index}>{index}</td>
                })
              }
            </tr>
          })
        }
        </tbody>
      </table>
    </p>)
  }
}
Copy after login

可以看到我们使用了一个星期数组作为表头,我们按照惯例是从周日开始的。你也可以从其他星期开始,不过会对下面的日期显示有影响,因为每个月的第一天是周几决定第一天显示在第几个格子里。

那为什么行数要6行呢?因为我们是按照最大行数来确定表格的行数的,如果一个月有31天,而这个月的第一天刚好是周六。就肯定会显示6行了。

为了显示好看,我直接写好了样式放置在index.html中了,这个不重要,不讲解。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style type="text/css">
        * {
            margin: 0;
            padding: 0;
        }
        .table {
            border-collapse:collapse;
            border-spacing:0;
        }
        .table td{
            border: 1px solid #ddd;
            padding: 10px;
        }
        .table caption .caption-header{
            border-top: 1px solid #ddd;
            border-right: 1px solid #ddd;
            border-left: 1px solid #ddd;
            padding: 10px;
            display: flex;
            justify-content: space-between;
        }
        .table caption .caption-header .arrow {
            cursor: pointer;
            font-family: "宋体";
            transition: all 0.3s;
        }
        .table caption .caption-header .arrow:hover {
            opacity:0.7;
        }
    </style>
</head>
<body>
    <p id="root"></p>
    <script src="./dist/main.js"></script>
</body>
</html>
Copy after login

下面就要开始显示日期了,首先要把当前月份的日期显示出来,我们先在组件的state中定义当前组件的状态

state = {
    month: 0,
    year: 0,
    currentDate: new Date()
}
Copy after login

我们定义一个方法获取当前年月,为什么不需要获取日,因为日历都是按月显示的。获取日现在看来对我们没有意义,于是新增一个方法,设置当前组件的年月

setCurrentYearMonth(date) {
    var month = Calendar.getMonth(date)
    var year = Calendar.getFullYear(date)
    this.setState({
      month,
      year
    })
}

static getMonth(date: Date): number{
    return date.getMonth()
}

static getFullYear(date: Date): number{
    return date.getFullYear()
}
Copy after login

创建两个静态方法获取年月,为什么是静态方法,因为与组件的实例无关,最好放到静态方法上去。

要想绘制一个月还需要知道一个月的天数吧,才好绘制吧

所以我们创建一个数组来表示月份的天数

const MONTH_DAYS = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]  // 暂定2月份28天吧
Copy after login

组件上创建一个函数,根据月份获取天数,也是静态的

static getCurrentMonthDays(month: number): number {
    return MONTH_DAYS[month]
}
Copy after login

下面还有一个重要的事情,就是获取当前月份第一天是周几,这样子就可以决定把第一天绘制在哪里了。首先要根据年月的第一天获得date,根据这个date获取周几。

static getDateByYearMonth(year: number, month: number, day: number=1): Date {
    var date = new Date()
    date.setFullYear(year)
    date.setMonth(month, day)
    return date
  }
Copy after login

这里获得每个月的第一天是周几了。

static getWeeksByFirstDay(year: number, month: number): number {
    var date = Calendar.getDateByYearMonth(year, month)
    return date.getDay()
  }
Copy after login

好了,开始在框子插入日期数字了。因为每个日期都是不一样的,这个二维数组可以先计算好,或者通过函数直接插入到jsx中间。

static getDayText(line: number, weekIndex: number, weekDay: number, monthDays: number): any {
    var number = line * 7 + weekIndex - weekDay + 1
    if ( number <= 0 || number > monthDays ) {
      return <span> </span>
    }

    return number
  }
Copy after login

看一下这个函数需要几个参数哈,第一个行数,第二个列数(周几),本月第一天是周几,本月天数。line * 7 + weekIndex表示当前格子本来是几,减去本月第一天星期数字。为什么+1,因为索引是从0开始的,而天数则是从1开始。那么<0 || >本月最大天数的则过滤掉,返回一个空span,只是为了撑开td。其他则直接返回数字。

import * as React from 'react'

const WEEK_NAMES = ['日', '一', '二', '三', '四', '五', '六']
const LINES = [1,2,3,4,5,6]
const MONTH_DAYS = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]

export default class Calendar extends React.Component {
  state = {
    month: 0,
    year: 0,
    currentDate: new Date()
  }

  componentWillMount() {
    this.setCurrentYearMonth(this.state.currentDate)
  }

  setCurrentYearMonth(date) {
    var month = Calendar.getMonth(date)
    var year = Calendar.getFullYear(date)
    this.setState({
      month,
      year
    })
  }

  static getMonth(date: Date): number{
    return date.getMonth()
  }

  static getFullYear(date: Date): number{
    return date.getFullYear()
  }

  static getCurrentMonthDays(month: number): number {
    return MONTH_DAYS[month]
  }

  static getWeeksByFirstDay(year: number, month: number): number {
    var date = Calendar.getDateByYearMonth(year, month)
    return date.getDay()
  }

  static getDayText(line: number, weekIndex: number, weekDay: number, monthDays: number): any {
    var number = line * 7 + weekIndex - weekDay + 1
    if ( number <= 0 || number > monthDays ) {
      return <span> </span>
    }

    return number
  }

  static formatNumber(num: number): string {
    var _num = num + 1
    return _num < 10 ? `0${_num}` : `${_num}`
  }

  static getDateByYearMonth(year: number, month: number, day: number=1): Date {
    var date = new Date()
    date.setFullYear(year)
    date.setMonth(month, day)
    return date
  }

  checkToday(line: number, weekIndex: number, weekDay: number, monthDays: number): Boolean {
    var { year, month } = this.state
    var day = Calendar.getDayText(line, weekIndex, weekDay, monthDays)
    var date = new Date()
    var todayYear = date.getFullYear()
    var todayMonth = date.getMonth()
    var todayDay = date.getDate()

    return year === todayYear && month === todayMonth && day === todayDay
  }

  monthChange(monthChanged: number) {
    var { month, year } = this.state
    var monthAfter = month + monthChanged
    var date = Calendar.getDateByYearMonth(year, monthAfter)
    this.setCurrentYearMonth(date)
  }

  render() {
    var { year, month } = this.state
    console.log(this.state)

    var monthDays = Calendar.getCurrentMonthDays(month)
    var weekDay = Calendar.getWeeksByFirstDay(year, month)

    return (

      {this.state.month}       

                                         {               WEEK_NAMES.map((week, key) => {                 return                })             }                                      {           LINES.map((l, key) => {             return                {                 WEEK_NAMES.map((week, index) => {                   return                  })               }                        })         }                
          

            <             {year} - {Calendar.formatNumber(month)}             >           

        
{week}
                    {Calendar.getDayText(key, index, weekDay, monthDays)}                   
    

)   } }
Copy after login

可以看到最终的代码多了一些东西,因为我加了月份的切换。

还记的上文我们把二月份天数写死的18天嘛?要不你们自己改改,判断一下闰年。

相关推荐:

React进行组件开发步骤详解

使用React如何进行组件库的开发


The above is the detailed content of Detailed explanation of how to develop calendar components using react. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What should I do if the win11 dual-screen calendar does not exist on the second monitor? What should I do if the win11 dual-screen calendar does not exist on the second monitor? Jun 12, 2024 pm 05:47 PM

An important tool for organizing your daily work and routine in Windows 11 is the display of time and date in the taskbar. This feature is usually located in the lower right corner of the screen and gives you instant access to the time and date. By clicking this area, you can bring up your calendar, making it easier to check upcoming appointments and dates without having to open a separate app. However, if you use multiple monitors, you may run into issues with this feature. Specifically, while the clock and date appear on the taskbar on all connected monitors, the ability to click the date and time on a second monitor to display the calendar is unavailable. As of now, this feature only works on the main display - it's unlike Windows 10, where clicking on any

What does placeholder mean in vue What does placeholder mean in vue May 07, 2024 am 09:57 AM

In Vue.js, the placeholder attribute specifies the placeholder text of the input element, which is displayed when the user has not entered content, provides input tips or examples, and improves form accessibility. Its usage is to set the placeholder attribute on the input element and customize the appearance using CSS. Best practices include being relevant to the input, being short and clear, avoiding default text, and considering accessibility.

What should I do if there are no pop-up reminders for calendar events in Win10? How to recover if calendar event reminders are gone in Win10 What should I do if there are no pop-up reminders for calendar events in Win10? How to recover if calendar event reminders are gone in Win10 Jun 09, 2024 pm 02:52 PM

The calendar can help users record your schedule and even set reminders. However, many users are asking what to do if calendar event reminders do not pop up in Windows 10? Users can first check the Windows update status or clear the Windows App Store cache to perform the operation. Let this site carefully introduce to users the analysis of the problem of Win10 calendar event reminder not popping up. To add calendar events, click the "Calendar" program in the system menu. Click the left mouse button on a date in the calendar. Enter the event name and reminder time in the editing window, and click the "Save" button to add the event. Solving the problem of win10 calendar event reminder not popping up

What does span mean in js What does span mean in js May 06, 2024 am 11:42 AM

The span tag can add styles, attributes, or behaviors to text. It is used to: add styles, such as color and font size. Set attributes such as id, class, etc. Associated behaviors such as clicks, hovers, etc. Mark text for further processing or citation.

What does rem mean in js What does rem mean in js May 06, 2024 am 11:30 AM

REM in CSS is a relative unit relative to the font size of the root element (html). It has the following characteristics: relative to the root element font size, not affected by the parent element. When the root element's font size changes, elements using REM will adjust accordingly. Can be used with any CSS property. Advantages of using REM include: Responsiveness: Keep text readable on different devices and screen sizes. Consistency: Make sure font sizes are consistent throughout your website. Scalability: Easily change the global font size by adjusting the root element font size.

How to introduce images into vue How to introduce images into vue May 02, 2024 pm 10:48 PM

There are five ways to introduce images in Vue: through URL, require function, static file, v-bind directive and CSS background image. Dynamic images can be handled in Vue's computed properties or listeners, and bundled tools can be used to optimize image loading. Make sure the path is correct otherwise a loading error will appear.

What language is the browser plug-in written in? What language is the browser plug-in written in? May 08, 2024 pm 09:36 PM

Browser plug-ins are usually written in the following languages: Front-end languages: JavaScript, HTML, CSS Back-end languages: C++, Rust, WebAssembly Other languages: Python, Java

What is node in js What is node in js May 07, 2024 pm 09:06 PM

Nodes are entities in the JavaScript DOM that represent HTML elements. They represent a specific element in the page and can be used to access and manipulate that element. Common node types include element nodes, text nodes, comment nodes, and document nodes. Through DOM methods such as getElementById(), you can access nodes and operate on them, including modifying properties, adding/removing child nodes, inserting/replacing nodes, and cloning nodes. Node traversal helps navigate within the DOM structure. Nodes are useful for dynamically creating page content, event handling, animation, and data binding.

See all articles