我正在尝试使用react-intl进行语言翻译。当我使用这个<FormattedMessage id='importantNews' />时,它工作得很好。但是,当我在intl.formatMessage()中使用以下代码时,它无法工作并抛出一些错误。我不知道里面出了什么问题。
import { injectIntl, FormattedMessage } from 'react-intl';
function HelloWorld(props) {
const { intl } = props;
const x = intl.formatMessage('hello') + ' ' + intl.formatMessage('world'); //not working
const y = <FormattedMessage id='hello' />; //working
return (
<button>{x}</button>
);
}
export default injectIntl(HelloWorld);我的根组件是这样的,
import ReactDOM from 'react-dom';
import { addLocaleData, IntlProvider } from 'react-intl';
import enLocaleData from 'react-intl/locale-data/en';
import taLocaleData from 'react-intl/locale-data/ta';
import HelloWorld from './hello-world';
addLocaleData([
...enLocaleData,
...taLocaleData
]);
const messages = {
en: {
hello: 'Hello',
world: 'World'
},
ta: {
hello: 'வணக்கம்',
world: 'உலகம்'
}
};
ReactDOM.render(
<IntlProvider key={'en'} locale={'en'} messages={messages['en']}>
<HelloWorld />
</IntlProvider>,
document.getElementById('root')
);有人能帮我解决这个问题吗?提前谢谢。
发布于 2017-06-30 03:49:16
您需要使用MessageDescriptor调用formatMessage,而不仅仅是id
const x = intl.formatMessage({id: 'hello'}) + ' ' + intl.formatMessage({id: 'world'});为了更好地记住这一点-组件是用prop id调用的
<FormatMessage id="Hello" />Props实际上是一个键值字典:
// this is the same as above
<FormatMessage {...{id: 'hello'}} />现在,formatMessage函数接受与FormatMessage组件相同的属性:
formatMessage({id: 'hello'})发布于 2020-08-18 17:50:50
此外,您似乎缺少它的默认值。
<FormattedMessage id="footer.table_no" defaultMessage="Hello" />发布于 2020-09-17 03:27:31
在尝试使用动态值并失败之后,我发现如果使用const intlKey = "something"
{intl.formatMessage({ id: intlKey })} //this doesn't work
{intl.formatMessage({ id: `${intlKey}` })} //this works<IntlMessages id={intlKey} /> //this doesn't work
<IntlMessages id={`${intlKey}`} /> //this works因此,为了让intl起作用,将你的值字符串化(即使确定它是一个字符串)。
https://stackoverflow.com/questions/44832683
复制相似问题