乐闻世界logo
搜索文章和话题

I am using ` react - i18next ` for translation and I need to give style to a certain part of string, how can I do that?

1个答案

1

When working with react-i18next for internationalization, if you need to style specific sections of translated strings, you can utilize the built-in Trans component. This component allows you to split translated text into multiple segments and apply distinct HTML tags or React components to each segment.

Suppose you have a requirement to add specific styles to nouns in translated text. First, you need to define translated strings with special markers in your translation file. For example, assume you have an English-to-Chinese translation file translation.json:

json
{ "welcome_message": "Welcome, <1>{{name}}</1>!" }

In this example, the <1>{{name}}</1> portion will be recognized by the Trans component as a replaceable and stylable element. The number 1 serves as a placeholder index that corresponds to the position in the array of child elements passed to the Trans component.

Next, use the Trans component in your React component and pass the corresponding elements:

jsx
import React from 'react'; import { useTranslation, Trans } from 'react-i18next'; function WelcomeMessage() { const { t } = useTranslation(); return ( <div> <Trans i18nKey="welcome_message" components={[<strong style={{ color: 'red' }} />]} > Welcome, <strong>{{name}}</strong>! </Trans> </div> ); }

In this example, <strong style={{ color: 'red' }} /> is the child element passed to the Trans component, which corresponds to the <1>{{name}}</1> in the translation text. As a result, {{name}} will be replaced with bold text in red.

By doing so, you can flexibly apply CSS styles or even more complex React components to any part of the translation.

2024年6月29日 12:07 回复

你的答案