我有一个标题徽标图像,其alt和标题属性应从i18n消息呈现。
message_en.json
{
"logoTitle": "Link open in new tab or window",
"logoAlt": "some description goes here.."
}
header.js
import { FormattedMessage } from 'react-intl/dist';
<a
href={url}
title={<FormattedMessage id="logoTitle"/>}
>
<img
src={src}
alt={<FormattedMessage id='logoAlt' />}
/>
</a>
在浏览器中,alt和title呈现为对象
<a title="[object Object]">
<img id="masthead__logo__img" src="../assets/images/logo.png" alt="[object Object]">
</a>
在这种情况下,如何呈现FormattedMessage?
发布于 2020-10-01 00:32:53
FormattedMessage
是一个呈现超文本标记语言的React组件。要呈现普通字符串,请改用intl.formatMessage
函数:
title={intl.formatMessage({ id: 'logoTitle' })}
发布于 2020-10-01 00:46:30
潜在的解决方案
使用useIntl
挂钩呈现一个普通字符串。
import { useIntl } from 'react-intl';
const intl = useIntl(); // place this within your function / class.
<a
href={url}
title={intl.formatMessage({ id: 'logoTitle' })} />}
>
<img
src={src}
alt={intl.formatMessage({ id: 'logoAlt' })} />}
/>
</a>
调试
您可以在属性外部执行console.log(intl.formatMessage({ id: 'logoTitle' });
,以查看为该标识符提取的值是什么。
https://stackoverflow.com/questions/64147538
复制相似问题