如何将 RectIntl 格式的消息添加为 html 属性
How to add RectIntl Formatted message as html attribute
我有一个 header 徽标图像,其 alt 和 title 属性应从 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 呈现为 [Object][Object]
<a title="[object Object]">
<img id="masthead__logo__img" src="../assets/images/logo.png" alt="[object Object]">
</a>
在这种情况下如何呈现 FormattedMessage?
FormattedMessage
是一个渲染 HTML 的 React 组件。要呈现纯字符串,请改用 intl.formatMessage
函数:
title={intl.formatMessage({ id: 'logoTitle' })}
可能的解决方案
使用 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' });
在 prop 之外查看为该标识符获取的值。
我有一个 header 徽标图像,其 alt 和 title 属性应从 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 呈现为 [Object][Object]
<a title="[object Object]">
<img id="masthead__logo__img" src="../assets/images/logo.png" alt="[object Object]">
</a>
在这种情况下如何呈现 FormattedMessage?
FormattedMessage
是一个渲染 HTML 的 React 组件。要呈现纯字符串,请改用 intl.formatMessage
函数:
title={intl.formatMessage({ id: 'logoTitle' })}
可能的解决方案
使用 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' });
在 prop 之外查看为该标识符获取的值。