首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何对连接的组件使用react-i18next

如何对连接的组件使用react-i18next
EN

Stack Overflow用户
提问于 2019-04-10 06:36:46
回答 5查看 8.1K关注 0票数 21

我想将react-i18next与我的react-redux连接组件一起使用,但不确定如何进行。

我简化了代码,显示了一个连接组件的示例:

代码语言:javascript
复制
import React from 'react';
import {connect} from 'react-redux';
import {userSelectors} from "./userSelectors";

interface IConnectedProps {
    activeUserName: string | undefined;
}
export class LandingPageComponent extends React.Component<IConnectedProps> {
    public render(): JSX.Element {
        return (
            <React.Suspense fallback={<Spinner/>}>
                <React.Fragment>
                    <div>
                    ... a bunch of controls using translated text
                    </div>
                    <div>{activeUserName}</div>
                </React.Fragment>
            </React.Suspense>
        );
    }
}

const mapStateToProps = (state: ICoreRootState) : IConnectedProps => ({
    activeUserName: userSelectors.getDisplayName(state),
});

export const LandingPage = connect(mapStateToProps)(LandingPageComponent);

已安装的程序包版本:

代码语言:javascript
复制
react version: 16.8.4 
react-redux version: 5.1.1 
react-i18next version: 10.6.0

我尝试过的:

1)当我使用withTranslation,WithTranslation时,得到如下错误:

代码语言:javascript
复制
export class LandingPageComponent extends React.Component<IConnectedProps & WithTranslation> {...}
export const LandingPage = connect(mapStateToProps)(withTranslation()(LandingPageComponent));

错误:

代码语言:javascript
复制
The above error occurred in the <withI18nextTranslation(LandingPageComponent)> component:
    in withI18nextTranslation(LandingPageComponent) (created by Connect(withI18nextTranslation(LandingPageComponent)))
    in Connect(withI18nextTranslation(LandingPageComponent))
    in Route
    in t
    in Connect(t) (at App.tsx:49)
    in Switch (at App.tsx:45)
    in App (at src/index.tsx:14)
    in Router (created by ConnectedRouter)
    in ConnectedRouter (created by Connect(ConnectedRouter))
    in Connect(ConnectedRouter) (at src/index.tsx:13)
    in Provider (at src/index.tsx:12)

2)当我使用withTranslation,WithTranslation时,得到如下错误:

代码语言:javascript
复制
export class LandingPageComponent extends React.Component<IConnectedProps & WithTranslation> {...}
export const LandingPage = withTranslation()(connect(mapStateToProps)(LandingPageComponent));

错误:

代码语言:javascript
复制
index.js:1446 The above error occurred in the <withI18nextTranslation(Connect(LandingPageComponent))> component:
    in withI18nextTranslation(Connect(LandingPageComponent))
    in Route
    in t
    in Connect(t) (at App.tsx:49)
    in Switch (at App.tsx:45)
    in App (at src/index.tsx:14)
    in Router (created by ConnectedRouter)
    in ConnectedRouter (created by Connect(ConnectedRouter))
    in Connect(ConnectedRouter) (at src/index.tsx:13)
    in Provider (at src/index.tsx:12)

3)我不能使用useTranslation,因为钩子不允许在类中使用。

我还尝试了以下几种方法:

代码语言:javascript
复制
... a bunch of imports
interface ILogoutButtonProps {
    userName?: string;
}
interface IConnectedHandlers {
    readonly logout: any;
    readonly push: any;
}
class InnerLogoutComponent extends React.Component<IButtonProps & IConnectedHandlers & ILogoutButtonProps & WithTranslation, {}> {

    public render() {
        const {userName, onClick, logout: Logout, push: Push, ...buttonProps} = this.props;
        const logoutText = this.props.i18n.t(StringNames.logout);
        const buttonText = userName ? logoutText + " " + userName : logoutText;
        return (
            <Button {...buttonProps} text={buttonText} onClick={this.handleClick}/>
        );
    }

    private handleClick = (event: React.MouseEvent<HTMLElement>) : void => {
        this.props.logout()
            .then(() => this.props.push(LoginPaths.verifyUser));
    }
}
const InnerLogoutTranslatedComponent = withTranslation()(InnerLogoutComponent);

class LogoutComponentInternal extends React.Component<IButtonProps & IConnectedHandlers & ILogoutButtonProps, {}> {
    public render () {
        return (
            <InnerLogoutTranslatedComponent {...this.props}/>
        );
    }
}
export const LogoutComponent = connect(null,{logout, push})(LogoutComponentInternal);

但我得到以下错误:

代码语言:javascript
复制
Hooks can only be called inside the body of a function component. 

先谢谢你……

EN

回答 5

Stack Overflow用户

发布于 2019-08-18 19:50:00

在我们的项目中,我们成功地利用了:

代码语言:javascript
复制
import { compose } from 'redux';
import { withNamespaces } from 'react-i18next';
import { connect } from 'react-redux';
...
export default compose(withNamespaces('translation'), connect(mapStateToProps))(ComponentName);

这样,我们就可以通过mapStateToProps连接到Redux,我们就有了translations

票数 5
EN

Stack Overflow用户

发布于 2019-10-31 23:00:17

我在RazzleJS中使用SSR,在我的情况下,它工作得很好。我是这样连接我的connectwithTranslation的:

代码语言:javascript
复制
export default connect(mapStateToProps,mapDispatchToProps)(withTranslation()(Component));
票数 3
EN

Stack Overflow用户

发布于 2019-05-27 23:20:05

实际上,我很难确定您在HOC中包装组件的顺序。在我目前工作的项目中,我们像withNamespaces(connect(withStyles(component)))一样包装,它工作得非常好(withNamespaces本质上和withTranslations是一样的)。我们在尝试连接已翻译的组件时遇到了问题,您现在可能也遇到了同样的问题。下面是我们的方法:

你有一个“正常”的组件,比如

代码语言:javascript
复制
type InjectedProps = StateProps & ExternalProps & MyComponentsTranslations
export class MyComponent extends React.Component<InjectedProps> {
    ...
} 

(注意:该过程与功能组件的工作方式完全相同)

你可以使用const MyConnectedComponent = connect(mapStateToProps, mapDispatchToProps)(MyComponent)

最后,你要做一个

代码语言:javascript
复制
import {WithNamespaces, withNamespaces} from "react-i18next"
export const LocalizedMyComponent = withNamespaces()(
  ({t,...rest}): WithNamepsaces) => (
    <MyConnectedComponent translations={{ put translations here }} {...rest} />
  )
)

现在,诀窍是我们定义了一个interface MyComponentsTranslations {},其中我们放置了所有需要的翻译或翻译函数(在复数的情况下)。将MyComponentsTranslations添加到InjectedProps中,以使它们在原始组件中可用。

您总是可以简单地将i18n的t-function注入到您的组件中,但在我当前的项目中,我们认为这样做更简洁

  • 显式命名component
  • Since所需的翻译无论是原始组件还是连通组件都不依赖于t函数它们非常容易测试

如果这对你有效,请告诉我。

此外,为了让整个过程更优雅一些,您可以使用这些助手:

代码语言:javascript
复制
export interface Translations<T> {
  translations: T
}

export const createTranslations = <T>(translations: T): Translations<T> => ({
  translations,
})

这允许您设置

代码语言:javascript
复制
type InjectedProps = StateProps & Translations<MyComponentTranslations>

withNamespace hoc中:

代码语言:javascript
复制
<MyConnectedComponent {...createTranslations<MyComponentTranslations>({ put translations here })} {...rest} />
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55602269

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档