简体   繁体   中英

convert from class to function react js

I'm working on a project, most of its components are classes, but I need to use Hooks, so i need to get ride of the classes and convert them to functional components, I know the basics about how to do it, but i get stuck of state and props this is one of the classes:

import React, { Component } from "react";
import { useHistory } from "react-router-dom";
class Description extends Component {
 render() {
  const handleSubmit = () => {
   this.props.completeTask(this.props.selectedTask, this.state);
  };
  const history = useHistory();
  return (
   <>
    <p>Completer donnees incident</p>
    <label for="description">Description:</label>
    <input
     type="text"
     id="description"
     name="description"
     onChange={(e) => this.setState({ emetteur: e.target.value })}
    />
    <br />

    <form action="/">
     <button type="button" className="btn btn-primary" onClick={handleSubmit}>
      Complete
     </button>
     <button
      type="button"
      className="btn btn-primary"
      onClick={history.goBack()}
     >
      Back
     </button>
    </form>
   </>
  );
 }
}

export default Description;

how can I use this in function:

 const handleSubmit = () => {
   this.props.completeTask(this.props.selectedTask, this.state);

You can destructure props in function component. Add useState to handle local state.

const Description = ({ selectedTask, completeTask }) => {
  const [state, setState] = useState({}); // local state

  const handleSubmit = () => {
    completeTask(selectedTask, state);
  };

  return (
    <>
      <p>Completer donnees incident</p>
      <label for="description">Description:</label>
      <input
        type="text"
        id="description"
        name="description"
        onChange={(e) => {
          setState({
            emetteur: e.target.value
          });
        }}
      />
      <br />

      <form action="/">
        <button
          type="button"
          className="btn btn-primary"
          onClick={handleSubmit}
        >
          Complete
        </button>
        <button
          type="button"
          className="btn btn-primary"
          onClick={history.goBack()}
        >
          Back
        </button>
      </form>
    </>
  );
};

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