React函数式组件中react-redux-i18n占位符翻译问题求助
Hey there! I’ve run into this exact issue before when working with react-redux-i18n in functional components using compose, so let’s break down what’s happening and how to fix it.
Why You’re Seeing an Object Instead of Text
The core difference between the two approaches is critical here:
i18n.tis a plain JavaScript function that spits out a translated string directly.- The
Translatecomponent is a React component, so when you use it (like<Translate ... />), it returns a React element object—not raw text. This works fine when you render it directly in JSX, but causes headaches if you try to use it where a string is expected (like passing it as a prop to a component that needs a string value).
Solutions to Get Your Placeholders Working
Here are two reliable fixes tailored to different use cases:
1. Use Render Props to Grab Raw Translated Text
If you need the translated string for a prop or non-JSX context, leverage the Translate component’s render prop pattern to access the plain text output:
import { Translate } from 'react-redux-i18n'; const SaveButton = () => { return ( <Translate value="button.save" params={{items: 5}}> {/* The render prop gives you direct access to the translated string */} {(translatedText) => <Button label={translatedText} />} </Translate> ); };
This way, you get the fully translated string (with placeholders replaced) to pass wherever you need it.
2. Render the Translate Component Directly in JSX
If you’re just displaying the translated text in your component’s output, rendering the Translate component directly in JSX will work perfectly—it’ll output the translated text as expected:
import { Translate } from 'react-redux-i18n'; const UserGreeting = () => { return ( <div className="greeting"> <Translate value="hello.user" params={{name: 'Andrey'}} /> </div> ); };
React will handle rendering the component’s output as text here, so your placeholders will be replaced correctly without any extra work.
Quick Check for Compose/Functional Components
Double-check that your component is wrapped in the Redux Provider (which it should be if you’re using react-redux-i18n) and that you’re on a recent version of the library—older versions might have quirks with placeholder handling in the Translate component.
That should get your translations working as intended! Let me know if you hit any other snags.
内容的提问来源于stack exchange,提问作者Andrey

