【问题标题】:How to get the component's return value如何获取组件的返回值
【发布时间】:2020-02-17 15:40:47
【问题描述】:

我有一些这样的代码:

import React from "react";
import "./styles.css";

const t = () => ["test1", "test2"];
const Translate = () => t("myText");

const MyComponent = ({ children }) => {
  console.log(children);
  return (
    children &&
    typeof children === "object" &&
    Array.isArray(children) &&
    children.map(val => (
      <>
        {`${val}__attached`}
        <br />
      </>
    ))
  );
};

export default function App() {
  return (
    <div className="App">
      <MyComponent>
        <Translate />
      </MyComponent>
    </div>
  );
}

当我检查控制台时,我打印了一个 React 元素。但我想要它的返回值。

例如,如果我替换这段代码:

    <MyComponent>
        <Translate />
    </MyComponent>

    <MyComponent>
        {t()}
    </MyComponent>

然后我在控制台上打印了一个包含 2 个对象的数组。我想在我的第一个案例中看到同样的输出。

我想要它,因为我想遍历 Translate 返回的值并根据它生成输出。

谢谢。

这里是codeandbox链接:

【问题讨论】:

    标签: reactjs internationalization i18next react-i18next


    【解决方案1】:

    你无法实现你想要的。实际上,当您编写 {t()} 时,您实际上提供了一个数组作为 MyComponent 的子元素,因此可以 map 其值。

    然而,一旦你写了&lt;Translate/&gt;MyComponent 的子元素就不再是一个数组,而是一个 React 元素(可以说是 HTML 元素)(在 MyComponent 中打印 children 以检查)进行测试总是假的(所以它什么也不打印)

    尝试在MyComponent 之外调用&lt;Translate/&gt;,您将看到页面上显示“test1test2”。它不再是一个数组。

    而不是这样写:

    <MyComponent> 
       <Translate />
    </MyComponent>
    

    我认为您应该采取相反的方式,以便能够轻松操纵来自Translate 的内容并将其传递给MyComponent

       <Translate>
          {values => <MyComponent values={values}>} 
       </Translate>
    

    Translate 是:

    const Translate = ({ children }) => children(t("myText"));
    
    

    MyComponent:

    const MyComponent = ({ values }) => {
      return (
        Array.isArray(values) &&
        values.map(val => (
          <>
            {`${val}__attached`}
            <br />
          </>
        ))
      );
    };
    
    

    现场演示here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多