簡體   English   中英

將反應類組件轉換為功能組件的快速方法?

[英]Fast way to convert react class component to functional component?

我有一個按預期工作的類組件,但現在我想將這個類組件更改為功能組件

這是我的課

import React, { Component } from 'react'
import EventCalendar from '../App';
import moment from 'moment';
import Row from 'react-bootstrap/Row';
import Col from 'react-bootstrap/Col';
import Button from 'react-bootstrap/Button';
import ButtonToolbar from 'react-bootstrap/ButtonToolbar';


const events =[
        {
            title: 'Womens History Month ',
            start: '2020-03-02',
            end: '2020-03-02',
            //description: '',
            url: 'dev91b558163211cf9d2e7d1efe6c3e32035973fdf9',
            eventClasses: 'event1'

        },
];

export class CalendarDemo extends Component {
    constructor(props) {
        super(props);

        this.state = {
            moment: moment(),

        };

        this.handleNextMonth = this.handleNextMonth.bind(this);
        this.handlePreviousMonth = this.handlePreviousMonth.bind(this);
        this.handleToday = this.handleToday.bind(this);
        this.handleEventClick = this.handleEventClick.bind(this);
        this.handleEventMouseOver = this.handleEventMouseOver.bind(this);
        this.handleEventMouseOut = this.handleEventMouseOut.bind(this);
        this.handleDayClick = this.handleDayClick.bind(this);
    }


    handleNextMonth() {
        this.setState({
            moment: this.state.moment.add(1, 'M'),
        });
    }

    handlePreviousMonth() {
        this.setState({
            moment: this.state.moment.subtract(1, 'M'),
        });
    }

    handleToday() {
        this.setState({
            moment: moment(),
        });
    }

    handleEventMouseOver(target, eventData, day) {
      console.log("event data", target.props.eventData.url);
        this.setState({

        });
    }

    handleEventMouseOut(target, eventData, day) {
        this.setState({

        });
    }

    handleEventClick(target, eventData, day) {
        this.setState({

        });
    }

    handleDayClick(target, day) {
        this.setState({

        });
    }

    getMomentFromDay(day) {
        return moment().set({
            'year': day.year,
            'month': (day.month + 0) % 12,
            'date': day.day,

        });
    }

    getHumanDate() {
        return [moment.months('MM', this.state.moment.month()), this.state.moment.year(), ].join(' ');
    }

    render() {

        return (
            <div style={styles}>

                    <Row className='topBar'>
                        <Col xs={6}>
                            <ButtonToolbar>
                                <Button onClick={this.handlePreviousMonth}>&lt;</Button>
                                <Button onClick={this.handleNextMonth}>&gt;</Button>
                                <Button onClick={this.handleToday}>Today</Button>
                            </ButtonToolbar>
                        </Col>
                        <Col xs={6}>
                            <div className='pull-right h2'>{this.getHumanDate()}</div>
                        </Col>
                    </Row>
                    <br />
                    <Row>
                        <Col xs={12}>
                            <EventCalendar
                                month={this.state.moment.month()}
                                year={this.state.moment.year()}
                                events={events} 
                                onEventClick={this.handleEventClick}
                                onEventMouseOver={this.handleEventMouseOver}
                                onEventMouseOut={this.handleEventMouseOut}
                                onDayClick={this.handleDayClick}
                                maxEventSlots={0}
                            />
                        </Col>
                    </Row>

            </div>
        );
    }
}

export default CalendarDemo

    const styles = {
            position: 'relative',
        };

我需要在這里更改什么才能獲得功能組件?

每個方法都必須改為const method = () => ... ,每個生命周期都必須改為useState/useEffectrender應該是功能組件的return值。

import React, { Component, useState } from 'react'
import EventCalendar from '../App';
import moment from 'moment';
import Row from 'react-bootstrap/Row';
import Col from 'react-bootstrap/Col';
import Button from 'react-bootstrap/Button';
import ButtonToolbar from 'react-bootstrap/ButtonToolbar';


const events =[
        {
            title: 'Womens History Month ',
            start: '2020-03-02',
            end: '2020-03-02',
            //description: '',
            url: 'dev91b558163211cf9d2e7d1efe6c3e32035973fdf9',
            eventClasses: 'event1'

        },
];

export const CalendarDemo = (props) => {
    const [_moment, updateMoment] = useState(moment());

    const handleNextMonth = () => {
        updateMoment(_moment.add(1, "M").clone());
    }

    const handlePreviousMonth = () => {
        updateMoment(_moment.subtract(1, "M").clone());
    }

    const handleToday = () => {
        updateMoment(moment());
    }

    const handleEventMouseOver = (target, eventData, day)  => {
        console.log("event data", target.props.eventData.url);
    }

    const handleEventMouseOut = (target, eventData, day) => {

    }

    const handleEventClick = (target, eventData, data) => {

    }

    const handleDayClick = (target, day) => {

    }

    const getMomentFromDay = day => {
        return moment().set({
            'year': day.year,
            'month': (day.month + 0) % 12,
            'date': day.day,

        });
    }

    const getHumanDate = () => {
        return [moment.months('MM', _moment.month()), _moment.year(), ].join(' ');
    }

    return (
        <div style={styles}>

                <Row className='topBar'>
                    <Col xs={6}>
                        <ButtonToolbar>
                            <Button onClick={handlePreviousMonth}>&lt;</Button>
                            <Button onClick={handleNextMonth}>&gt;</Button>
                            <Button onClick={handleToday}>Today</Button>
                        </ButtonToolbar>
                    </Col>
                    <Col xs={6}>
                        <div className='pull-right h2'>{getHumanDate()}</div>
                    </Col>
                </Row>
                <br />
                <Row>
                    <Col xs={12}>
                        <EventCalendar
                            month={_moment.month()}
                            year={_moment.year()}
                            events={events} 
                            onEventClick={handleEventClick}
                            onEventMouseOver={handleEventMouseOver}
                            onEventMouseOut={handleEventMouseOut}
                            onDayClick={handleDayClick}
                            maxEventSlots={0}
                        />
                    </Col>
                </Row>

        </div>
    );
}

export default CalendarDemo

    const styles = {
            position: 'relative',
        };
  • 將每個類方法func轉換為內部函數(使用function func() {}或使用const func = () => {}
  • 將您狀態中的每個屬性attr轉換為const [attr, setAttr] = useState()調用。 然后用attr替換對this.state.attr每次調用,用setAttr(newValue)替換對this.setState({attr: newValue})每次調用
  • 保持您的render()函數大部分不變,只需刪除外部函數,刪除所有this. 引用函數時的前綴並替換對this.state每個引用,如上所述
  • (在您的示例中不存在):用useEffect替換componentDidMount
  • function CalendarDemo()替換class CalendarDemo extends Component (使用箭頭語法,如果你喜歡)

筆記:

  • this.state綁定需要轉換為useState鈎子
  • 您需要導出一個function而不是Class作為default export
  • 我沒有添加 onHandleClick 方法,因為示例中沒有提供它們。
import React, { useState, Component } from "react"
import EventCalendar from '../App';
import moment from 'moment';
import Row from 'react-bootstrap/Row';
import Col from 'react-bootstrap/Col';
import Button from 'react-bootstrap/Button';
import ButtonToolbar from 'react-bootstrap/ButtonToolbar';

const events = [
  {
    title: 'Womens History Month ',
    start: '2020-03-02',
    end: '2020-03-02',
    //description: '',
    url: 'dev91b558163211cf9d2e7d1efe6c3e32035973fdf9',
    eventClasses: 'event1'

  },
];

const CalendarComponent = (props) => {

  const [momentState, updateMoment] = useState(moment())

  const handlePreviousMonth = () => updateMoment(moment().subtract(1, 'M'));
  const handleNextMonth = () => updateMoment(moment().add(1, 'M'));
  const handleToday = () => updateMoment(moment())

  const getHumanDate = () => {
    return [
      moment.months('MM', momentState.month()),
      momentState.year(),
    ].join(' ');
  }

  // todo
  // const handleEventClick = 
  // const handleEventMouseOver = 
  // const handleEventMouseOut = 
  // const handleDayClick = 

  return (
    <div >

      <Row className='topBar'>
        <Col xs={6}>
          <ButtonToolbar>
            <Button onClick={handlePreviousMonth}>&lt;</Button>
            <Button onClick={handleNextMonth}>&gt;</Button>
            <Button onClick={handleToday}>Today</Button>
          </ButtonToolbar>
        </Col>
        <Col xs={6}>
          <div className='pull-right h2'>{getHumanDate()}</div>
        </Col>
      </Row>
      <br />
      <Row>
        <Col xs={12}>
          <EventCalendar
            month={momentState.month()}
            year={momentState.year()}
            events={events}
            // onEventClick={handleEventClick}
            // onEventMouseOver={handleEventMouseOver}
            // onEventMouseOut={handleEventMouseOut}
            // onDayClick={handleDayClick}
            maxEventSlots={0}
          />
        </Col>
      </Row>

    </div >
  );
}


export default CalendarComponent

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM