TabPanel: 警告:validateDOMNesting(...): <div> 不能作为 <p> 的后代出现

10
当我使用Material-UI中的选项卡时,代码可以正常工作,但当我使用网格和排版自定义TabPanel时,遇到了这个警告。我理解问题在于<div>不能放置在<p>内,但需要解决方案来自定义TabPanel。
我需要类似以下的内容:
<TabPanel value={value} index={0}>
    <Grid>
      <Grid>Item One</Grid>
    </Grid>
  </TabPanel>

这是我尝试过的代码示例:

import React from "react";
import PropTypes from "prop-types";
import { makeStyles } from "@material-ui/core/styles";
import AppBar from "@material-ui/core/AppBar";
import Tabs from "@material-ui/core/Tabs";
import Tab from "@material-ui/core/Tab";
import Typography from "@material-ui/core/Typography";
import Box from "@material-ui/core/Box";
import Grid from "@material-ui/core/Grid";

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

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

TabPanel.propTypes = {
  children: PropTypes.node,
  index: PropTypes.any.isRequired,
  value: PropTypes.any.isRequired
};

function a11yProps(index) {
  return {
    id: `simple-tab-${index}`,
    "aria-controls": `simple-tabpanel-${index}`
  };
}

const useStyles = makeStyles((theme) => ({
  root: {
    flexGrow: 1,
    backgroundColor: theme.palette.background.paper
  }
}));

export default function SimpleTabs() {
  const classes = useStyles();
  const [value, setValue] = React.useState(0);

  const handleChange = (event, newValue) => {
    setValue(newValue);
  };

  return (
    <div className={classes.root}>
      <AppBar position="static">
        <Tabs
          value={value}
          onChange={handleChange}
          aria-label="simple tabs example"
        >
          <Tab label="Item One" {...a11yProps(0)} />
          <Tab label="Item Two" {...a11yProps(1)} />
          <Tab label="Item Three" {...a11yProps(2)} />
        </Tabs>
      </AppBar>
      <TabPanel value={value} index={0}>
        <Grid>
          <Grid>Item One</Grid>
        </Grid>
      </TabPanel>
      <TabPanel value={value} index={1}>
        Item Two
      </TabPanel>
      <TabPanel value={value} index={2}>
        Item Three
      </TabPanel>
    </div>
  );
}

我在这里找到了一个相关的问题,它在mui-org/material-ui git issue上。

2个回答

11

将位于树上方的<Typography>组件移除,并将其放入子元素中;Typography会在<p>标签内呈现其子元素,这会导致错误。


哇,MUI需要在这方面更新他们的文档。谢谢。 - Sean

2

你可以直接用以下内容替换它:

<Typography component={"div"}>{children}</Typography>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接