我有一个 React 组件,它是 Context Provider 的消费者。我将其用于国际化的翻译组件。我的消费者基本上是 React Context Consumer 元素的包装器,并调用底层的翻译函数。我的问题是,我只想从这个组件返回 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');