[英]Is there a way to return React Component as string instead of object?
I want to introduce a multilingual system.我想介绍一个多语言系统。 I have a function component that returns a translation of a specific element based on selected language (from Context API).我有一个函数组件,它根据所选语言(来自 Context API)返回特定元素的翻译。
Everything works well until I put the translated element into the form (option value, placeholder, etc.) - then it appears as an [object object].一切正常,直到我将翻译的元素放入表单(选项值、占位符等) - 然后它显示为 [object object]。
That's where 2 questions are born:这就是2个问题诞生的地方:
Is it possible to return this component as a something like string, which HTML forms would accept?是否可以将此组件作为字符串之类的东西返回,哪些 HTML 表单会接受?
Is it possible to apply context consumer to pure JS function, so it does not return a React component, but a primitive value?是否可以将上下文消费者应用于纯 JS 函数,因此它不返回 React 组件,而是返回原始值?
Translation component:翻译组件:
const Translation = ({ element }) => {
let translation;
return (
<LanguageConsumer>
{({ language }) => {
switch (language) {
case "pl":
translation = plTranslation;
break;
case "en":
translation = enTranslation;
break;
default:
translation = enTranslation;
}
return translation[element];
}}
</LanguageConsumer>
);
};
Example:例子:
<option value="en">
<Translation element="globalLanguageEnglish" />
</option>
Thanks in advance for your help.在此先感谢您的帮助。
I can confirm it doesn't work - <option>
html element content can be "Text, possibly with escaped characters (like é
)."我可以确认它不起作用 - <option>
html 元素内容可以是“文本,可能带有转义字符(如é
)。”
React component can return only string, it's perfectly valid (and works as OP stated) ... but this use case is not supported . React 组件只能返回字符串,它完全有效(并按 OP 所述工作)……但不支持此用例。
Using components to just return a string is not a good choice .使用组件只返回一个字符串并不是一个好的选择。 It can be ineffective when you need many translated strings in one component.当您在一个组件中需要许多已翻译的字符串时,它可能无效。 React has to manage it as components, control props, render, make reconcilation etc. Many, following components (siblings) of the same type (only different props) should be key
-ed. React 必须将其作为组件进行管理,控制道具,渲染,进行协调等。许多相同类型(仅不同道具)的后续组件(兄弟姐妹)应该被key
。
Smarter solution : In this case pass an array of options (keys) as prop and use one component to render all translated <option>
elements in a loop (return using fragment), fe like this:更智能的解决方案:在这种情况下,将一组选项(键)作为道具传递并使用一个组件在循环中呈现所有翻译的<option>
元素(使用片段返回),如下所示:
// get some translation fn f.e. from context
return (
<>
{props.items.map( item => <option key="{item}" value="{item}">{translate(item)}</option> )}
</>
)
Look how it's done at ready i18n solutions like i18next
described here - pass function 't'
and use it to access your translations.看看它是如何在国际化做好准备的解决方案做过类似i18next
描述这里-通功能't'
,并用它来访问您的翻译。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.