【问题标题】:How to use the t() function in a class component with a constructor?如何在具有构造函数的类组件中使用 t() 函数?
【发布时间】:2021-10-21 06:32:54
【问题描述】:

i18next配合react使用,我想在类组件中使用t()函数,但大多数时候,我还需要初始化状态,所以我也想有一个构造函数。

按照documentation here 我明白了:

import React from 'react';
import {WithTranslation, withTranslation} from "react-i18next";

interface ExampleProps extends WithTranslation {

}

interface ExampleState {

}

class Example extends React.Component<ExampleProps, ExampleState> {
    render() {
        const t = this.props.t;
        return (
            <div>
                <p>{t('Test')}</p>
            </div>
        );
    }
}

export default withTranslation()(Example);

这工作正常,这里没问题。直到我添加一个构造函数:

    constructor(props: ExampleProps, context: any) {
        super(props, context);
    }

withTranslation 不适用于此:

TS2345: Argument of type 'typeof Example' is not assignable to parameter of type 'ComponentType<WithTranslationProps>'.   Type 'typeof Example' is not assignable to type 'ComponentClass<WithTranslationProps, any>'.     Types of parameters 'props' and 'props' are incompatible.       Type 'WithTranslationProps' is missing the following properties from type 'WithTranslation<"translation">': t, tReady

如果我使用interface ExampleProps extends WithTranslationProps {},则类型不兼容会消失,但我无法访问t 函数,因为WithTranslationProps 只有i18n? 可空类型,我无法向@987654334 添加任何内容@,因为我得到了Property 'newProperty' is missing in type 'WithTranslationProps' but required in type 'ExampleProps'.

const t1 = this.props.i18n?.t; 在尝试调用 t('Test') 时会产生 TS2722: Cannot invoke an object which is possibly 'undefined'

const t2 = this.props.t; 不存在。

一种解决方案,如果我只是直接在类中初始化状态,比如:

class Example extends React.Component<ExampleProps, ExampleState> {
    state = {
      // set state here
    }

    render() {

虽然我还是想知道这里有没有办法使用构造函数。

【问题讨论】:

    标签: reactjs typescript i18next react-i18next


    【解决方案1】:

    来自 React documentation

    如果您不初始化状态并且不绑定方法,则不需要为您的 React 组件实现构造函数。

    但是,等一下,你传递给constructorcontext 是什么?

    您只需将props 作为constructor 的参数传递即可。

    构造函数(道具)

    【讨论】:

    • 是的。我使用 IDE 自动生成了构造函数,因此有两个参数。如果我只通过道具,一切都会按预期进行。谢谢。
    【解决方案2】:

    根据documentation,在 react 构造函数和超级方法中接收 0 个参数或 1(如果是 1,那么它们应该是 props)

    在你的渲染中你可以这样做

    render () {
       const { t } = this.props;
    
       return (
                <div>
                    <p>{t('Test')}</p>
                </div>
            );
    }
    

    组件 props 的这种解构使您的代码更具可读性,如果您需要来自 props 的更多变量,只需添加一个逗号和变量的名称,它就可以在该函数中使用。

    除了你的代码看起来不错

    【讨论】:

      猜你喜欢
      • 2020-05-25
      • 1970-01-01
      • 1970-01-01
      • 2017-11-23
      • 2021-01-23
      • 1970-01-01
      • 2021-09-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多