【发布时间】: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