简体   繁体   中英

I am trying to change this React class component into a Functional Component

The reason why I want to is, I am used to functional components, and the rest of my code is written with functional components so I'd like to keep it that way. I have actually never learned class components (I am still very new with coding), we just went in with Functional components, perhaps because of the React Hooks, and although I have read things online, I am having a hard time trying to convert this. This is the code I am trying to convert:

 import React, { Component } from 'react'; import Calendar from 'react-calendar'; class MyApp extends Component { state = { date: new Date(), } onChange = date => this.setState({ date }) render() { return ( <div> <Calendar onChange={this.onChange} value={this.state.date} /> </div> ); } } export default Calendar;
I've only managed to convert some of it to a functional component like this:

 import React {useState} from "react"; import Calendar from "react-calendar"; export default function Calendar () { const[date, setDate] = useState({date: new Date()})
I am even unsure if what I started is correct, but this is all I have so far with converting. I don't know how to convert the rest.

import React, { useState } from 'react';
import Calendar from 'react-calendar';

export default () => {
  const[date, setDate] = useState({date: new Date()});
  return (
    <div>
      <Calendar
        onChange={date => setDate({ date })}
        value={date}
      />
    </div>
  );
}
import React, { useState} from 'react';
import Calendar from 'react-calendar';

 const Calendar = () => {
 const[date, setDate] = useState({new Date()});

  onChange = date => setDate(date);

  render() {
    return (
      <div>
        <Calendar
          onChange={this.onChange}
          value={date}
        />
      </div>
    );
  }
}

export default Calendar;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM