如何将功能组件转换为类组件?

时间:2020-08-16 07:41:09

标签: reactjs

我是React.js的新手,我试图将功能性组件转换为类组件,有人可以帮助我吗? 这是我的代码,我想将功能组件中的代码转换为类组件

import React, { useState, useRef } from 'react';
import  {DateRangePicker}  from 'react-date-range';
import 'react-date-range/dist/styles.css'; // main style file
import 'react-date-range/dist/theme/default.css'; // theme css file
import { addDays } from 'date-fns';
import { useState } from 'react';
function App(){
const [state, setState] = useState([
  {
    startDate: new Date(),
    endDate: addDays(new Date(), 7),
    key: 'selection'
  }
]);
return(
<DateRangePicker
  onChange={item => setState([item.selection])}
  showSelectionPreview={true}
  moveRangeOnFirstSelection={false}
  months={2}
  ranges={state}
  direction="horizontal"
/>
);
}

有人可以帮助我解决此问题吗?

2 个答案:

答案 0 :(得分:1)

import React from 'react';
import { DateRangePicker } from 'react-date-range';
import 'react-date-range/dist/styles.css'; // main style file
import 'react-date-range/dist/theme/default.css'; // theme css file
import { addDays } from 'date-fns';

class App extends React.Component {
  
  state = {
    startDate: new Date(),
    endDate: addDays(new Date(), 7),
    key: 'selection'
  };
  
  handleDateSelect = (item) => {
    this.setState({
      ...item
    });
  }

  render() {
    const { startDate, endDate, key } = this.state;

    return (
      <DateRangePicker
        onChange={item => this.handleDateSelect(item)}
        showSelectionPreview={true}
        moveRangeOnFirstSelection={false}
        months={2}
        ranges={{
          startDate,
          endDate,
          key
        }}
        direction="horizontal"
      />
    );
  }
}

export default App;

答案 1 :(得分:1)

编辑:要修复“ TypeError:ranges.findIndex不是函数” 错误,您应将数组中的 selectionRange 放置到道具。

赞: ranges={ [ this.state.selectionRange ] }

不是这样的:ranges={ this.state.selectionRange }

有关更多信息,请在此处查看示例:react-date-range - npm

我想你也应该在这里检查:Function and Class Components

import React from "react";
import { DateRangePicker } from "react-date-range";
import "react-date-range/dist/styles.css"; // main style file
import "react-date-range/dist/theme/default.css"; // theme css file
import { addDays } from "date-fns";

class ComponentName extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      selectionRange: {
        startDate: new Date(),
        endDate: addDays(new Date(), 7),
        key: "selection"
      }
    }
  }

  render() {
    return (
      <DateRangePicker
        onChange={(item) => this.setState({selectionRange: item.selection})}
        showSelectionPreview={true}
        moveRangeOnFirstSelection={false}
        months={2}
        ranges={[this.state.selectionRange]}
        direction="horizontal"
      />
    );
  }
}