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

Vis*_*kar 3 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>
      ))}
    </>
  )
}
Run Code Online (Sandbox Code Playgroud)

Moh*_*ami 5

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

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

  • 或者在不更改他的代码的情况下: `{ "component":AnotherComponent}` 变为 `{ "component": &lt;AnotherComponent /&gt;}` 因为他循环的重点是能够传递该“tabItem” (2认同)