React 将函数组件转换为 class 组件

React convert function component to class component

我正在使用 react react-i18next 包进行语言翻译。

我的函数组件没有任何错误

import React, { Suspense } from 'react';
import { useTranslation } from 'react-i18next';

function MyComponent() {
  const { t, i18n } = useTranslation();

  return (<Suspense fallback="loading">
           <h1>{t('Welcome to React')}</h1>
          </Suspense>);
}

export default MyComponent;

当我尝试将其转换为 class 时,如下所示

import React, { Component, Suspense } from 'react';
import { useTranslation } from 'react-i18next';

class MyComponent extends Component {
    constructor(props) {
        super(props);
    }
    render() {
        const { t, i18n } = useTranslation();
        return (
        <Suspense fallback="loading">
            <h1>{t('hello')}</h1>
        </Suspense>
        );
    }
}

export default MyComponent;

我收到错误

Invalid hook call. Hooks can only be called inside of the body of a >function component. This could happen for one of the following reasons:

谁能指出我做错了什么?

useTranslation 是一个 hook,只能从基于 function 的组件中调用。对于基于 class 的组件,使用 HOC

import { withTranslation } from 'react-i18next';

class Comp extends Component{
    render(){
        const { t, i18n } = this.props

        return <SomeJSX />
    }
}

export default withTranslation()(Comp)

注意也可以在功能组件中使用withTranslation