将类组件转换为功能组件

时间:2020-02-22 14:52:08

标签: reactjs typescript function class redux

我已经用React Redux和TypeScript创建了一个Web应用程序项目。 (在VS 2019中)。

为我创建了一个模板项目,该项目只有几个类组件(Counter,WeatherForecast ....)。 现在,我正在尝试将类组件-Counter-转换为Function组件。 目前没有成功。 我需要帮助。

class组件是:

import * as React from 'react';
import { connect } from 'react-redux';
import { RouteComponentProps } from 'react-router';
import { ApplicationState } from '../store';
import * as CounterStore from '../store/Counter';

type CounterProps =
    CounterStore.CounterState &
    typeof CounterStore.actionCreators &
    RouteComponentProps<{}>;

class Counter extends React.PureComponent<CounterProps> {
    public render() {
        return (
            <React.Fragment>
                <h1>Counter</h1>

                <p>This is a simple example of a React component.</p>

                <p aria-live="polite">Current count: <strong>{this.props.count}</strong></p>

                <button type="button"
                    className="btn btn-primary btn-lg"
                    onClick={() => { this.props.increment(); }}>
                    Increment
                </button>
            </React.Fragment>
        );
    }
};

export default connect(
    (state: ApplicationState) => state.counter,
    CounterStore.actionCreators
)(Counter);

1 个答案:

答案 0 :(得分:0)

感谢您的回复。我知道应该怎么做:

type CounterComponentProps =
     CounterStore.CounterState &
     typeof CounterStore.actionCreators &
     RouteComponentProps<{}>;

const Counter = (props: CounterComponentProps) => {

    return (
        <React.Fragment>

          <h1>Counter</h1>

          <p>This is a simple example of a React component.</p>

          <p aria-live="polite">Current count: <strong>{props.count}</strong></p>

          <button type="button"
                className="btn btn-primary btn-lg"
                onClick={() => { props.increment(); }}>
                Increment
          </button>
      </React.Fragment>
    );

};

export default connect(
    (state: ApplicationState) => state.counter,
    CounterStore.actionCreators)(Counter as any)