我有一个React组件,它是Context Provider的使用者。我将此用于国际化的翻译组件。我的使用者基本上是React Context使用者元素的包装器,并调用了底层转换函数。我的问题是,我只想从该组件返回STRING值,但实际上它返回的是一个React元素,它破坏了我的界面。可以“解开”这个字符串并只给我字符串吗?
import * as React from 'react';
import {IIntlContext, IntlContext} from 'Common/Intl/IntlProvider';
export default (key: string) => {
// I JUST WANT THE STRING!
return (
<IntlContext.Consumer>
{
(context: IIntlContext) => {
return context.translate(key);
}
}
</IntlContext.Consumer>
);
};
提供者包装了我的整个React应用,看起来像这样:
import * as React from 'react';
interface IIntlProviderProps {
locale: string;
i18n: any;
children: React.ReactNode;
}
interface IIntlProviderState {
locale: string;
i18n: any;
}
export interface IIntlContext extends IIntlProviderState {
translate: (key: string) => any;
}
export const IntlContext = React.createContext<IIntlContext | undefined>(
undefined
);
export class IntlProvider extends React.Component<IIntlProviderProps, IIntlProviderState> {
constructor(props: IIntlProviderProps) {
super(props);
this.state = {
locale: props.locale,
i18n: props.i18n
};
}
public translate = (key: string) => {
return this.state.i18n.t(key);
};
public render() {
const context: IIntlContext = {
...this.state,
translate: this.translate
};
return (
<IntlContext.Provider value={context}>
{this.props.children}
</IntlContext.Provider>
);
}
}
export default IntlProvider;
我的目标是仅能够导入使用者并将其传递给字符串以进行这样的翻译:
import translate from 'Common/Intl/Translator';
translate('some text');