【问题标题】:convert from class to function react js从类转换为函数反应js
【发布时间】:2021-02-13 11:33:43
【问题描述】:

我正在做一个项目,它的大部分组件都是类,但我需要使用 Hooks,所以我需要使用这些类并将它们转换为功能组件, 我知道如何做的基础知识,但我被状态和道具卡住了 这是其中的一类:

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;

如何在函数中使用它:

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

【问题讨论】:

    标签: javascript reactjs react-component


    【解决方案1】:

    你可以在函数组件中解构 props。添加useState 处理本地状态。

    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>
        </>
      );
    };
    

    【讨论】:

      猜你喜欢
      • 2020-02-14
      • 1970-01-01
      • 1970-01-01
      • 2018-12-16
      • 1970-01-01
      • 1970-01-01
      • 2019-02-02
      • 2015-09-01
      • 2020-08-06
      相关资源
      最近更新 更多