【问题标题】:How to pass a react component as a variable, to child component?如何将反应组件作为变量传递给子组件?
【发布时间】:2020-01-22 16:02:33
【问题描述】:

当我在变量中定义了一个组件,并尝试将它作为子属性传递给组件时,会显示Objects are not valid as a React child 错误。

这样做的正确方法是什么?

function AnotherComponent(){
  return "Another";
}

function ChildComponent(props) {
  const { children, value, index, ...other } = props;

  console.log(children);
  return (
    <Typography
      component="div"
      role="tabpanel"
      hidden={value !== index}
      id={`full-width-tabpanel-${index}`}
      aria-labelledby={`full-width-tab-${index}`}
      {...other}
    >
      <Box p={3}>{children}</Box>
    </Typography>
  );
}

function MainComponent(){
  const tabItems = [
    { "component": AnotherComponent}
  ];

  const [value, setValue] = React.useState(0);

  return (
    <>
      {tabItems.map((tabItem,index) => (
        <ChildComponent value={value} index={tabItem.index}>
          {tabItem.component}
        </ChildComponent>
      ))}
    </>
  )
}

【问题讨论】:

    标签: reactjs material-ui react-hooks


    【解决方案1】:

    tabItem.component 只是一个对象。这应该有效:

    {tabItems.map((tabItem, index) => {
        const TheComponent = tabItem.component;
        return (
          <TabPanel value={value} index={tabItem.index}>
            <TheComponent />
          </TabPanel>
        );
      })}
    

    【讨论】:

    • 或者不改变他的代码:{ "component":AnotherComponent} 变成{ "component": &lt;AnotherComponent /&gt;} 因为他的循环的重点是能够传递那个“tabItem”
    • 这似乎不起作用——虽然这段代码没有呈现AnotherComponent,但错误是不可见的。 ` {tabItems.map((tabItem,index) => { let TabComponent = tabItem.component; return TabPanel> })} `
    • TabPanel 是什么?问题可能在那里
    • 嗯,TabPanel 应该是ChildComponent,更正了代码
    • 它显示如下 - $$typeof: Symbol(react.element) key: null props: {} ref: null type: {$$typeof: Symbol(react.forward_ref), displayName: “WithSnackbar(WithStyles(Clip))”,选项:{...},渲染:ƒ,裸体:ƒ,...} ....
    【解决方案2】:

    问题在于您初始化数组的方式实际上只是将一个函数分配给它。正如错误所说 - 你不能渲染一个函数。您必须将该函数包装到 JSX 语法中才能完成整个 React.createChild 事情。

    所以只要改变这一行

     const tabItems = [
    { "component": AnotherComponent}
    ];
    

    到这里:

     const tabItems = [
    { "component": <AnotherComponent />}
    ];
    

    它会像魅力一样发挥作用。 :)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-05-30
      • 2016-05-26
      • 2019-01-02
      • 1970-01-01
      • 1970-01-01
      • 2020-07-23
      • 2018-04-15
      相关资源
      最近更新 更多