如何将 React 上下文 API 中的变量插入到占位符中?

How can I insert a variable from the React context API into a placeholder?

我正在使用 React Context API 以多种语言显示我的网站。除了当我尝试在我的文本区域中插入占位符时,一切正常,它显示 [object Object]。如果我在实际中使用相同的组件,例如在

标签中,它会正确显示!

import React, { Component } from "react";
import Translate from '../translations/Translate'

class FormEntry extends Component {
  render() {
    return (
      <div className="inputArea shadow">
        <textarea
          className="dataInputChild"
          placeholder={<Translate string={'submitbox.copy-and-paste'}/>}//this displays [object Object]
        />
        <p><Translate string={'submitbox.copy-and-paste'}/></p> //this displays the desired text
      </div>
    );
  }
}
export default FormEntry;

翻译组件如下:

import React, { PureComponent } from "react";
import en from "./en.json";
import es from "./es.json"; //these are the dictionary files
import cn from "./cn.json";
LanguageContext = React.createContext()

export default class Translate extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      langs: {
        en,
        es,
        cn
      }
    };
  }
  render() {
      const {langs} = this.state 
      const {string} = this.props
    return (
      <LanguageContext.Consumer>
        {value => langs[value][string]}
      </LanguageContext.Consumer>
    );
  }
}

谁能看出我做错了什么?

谢谢!

<Translate string={'submitbox.copy-and-paste'}/>是React元素,是一个对象。它不能作为 placeholder 属性提供,因为需要一个字符串。

FormEntry 组件可以使用 contextType 来访问上下文。这限制了组件使用单个上下文。

只是为了扩展 ,只需创建一个单独的函数来接受语言、语言值和字符串(就像您在 render 中的 Translate 组件中所做的那样方法)并在你需要的任何地方重复使用它。

您会将上下文与实际功能分开,您可以像这样重用函数: (或在您有权访问上下文的任何其他组件中)。

// langs -> coming from context or some map of languages you use
// langValue -> coming from the context API
// 'submitbox.copy-and-paste' -> the actual string you want to translate

const translation = translate(langs, langValue, 'submitbox.copy-and-paste');
// and then use the variable in as placeholder and the <p> tag
// or if different string values see below

<div className="inputArea shadow">
   <textarea 
      className="dataInputChild" 
      placeholder={translate(langs, langValue, 'submitbox.copy-and-paste')}
   />
   <p>{translate(langs, langValue, 'submitbox.copy-and-paste')}/></p>
</div>