如何将react组件作为变量传递给子组件?

时间:2019-09-22 09:37:44

标签: reactjs material-ui react-hooks

当我在变量中定义了一个组件,并试图将其作为子项传递给组件时,将显示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>
      ))}
    </>
  )
}

2 个答案:

答案 0 :(得分:4)

tabItem.component只是一个对象。这应该可以工作:

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

答案 1 :(得分:0)

问题是初始化数组的方式实际上只是在其中分配一个函数。就像错误所说的一样-您无法渲染函数。您必须将该函数包装为JSX语法才能完成整个React.createChild

所以只需更改此行

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

对此:

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

,它将像魅力一样工作。 :)