MUI v5:失败的道具类型:`Grid`的道具`direction`只能与`container`道具一起使用

Posted

技术标签:

【中文标题】MUI v5:失败的道具类型:`Grid`的道具`direction`只能与`container`道具一起使用【英文标题】:MUI v5: Failed prop type: The prop `direction` of `Grid` can only be used together with the `container` prop 【发布时间】:2021-12-01 05:20:59 【问题描述】:

我正在设计 MUI v5 Grid,如下所示:

const SettingsGrid = styled(Grid)(( theme ) => (
    width: `calc(100% - calc($Number(theme.spacing(2)) * 2))`,
    margin: theme.spacing(2),

    '& .MuiCard-root + .MuiTypography-subtitle1': 
        marginTop: theme.spacing(4),
    ,
))

那么,我是这样使用的:

<Box m=1 overflow="auto">
  <SettingsGrid
      container
      direction="row"
      justifyContent="center"
  >
      <Grid
          direction="column"
          style= minWidth: '35em', maxWidth: '60em' 
      >
          <!-- ... -->
      </Grid>
    </SettingsGrid>
</Box>

这会在运行时抛出这个控制台警告:

Failed prop type: The prop `direction` of `Grid` can only be used together with the `container` prop.

我试过container=true,但这没有帮助。似乎container 属性在styled() 中丢失了。我怎样才能解决这个问题?我很茫然。

伊迪丝:https://codesandbox.io/s/gritty-styled-grid-7l04g

【问题讨论】:

请提供code sandbox 重现问题。 @TheDiveO 尝试在内部Grid 中设置container,我认为您在那里缺少container 道具。在 Codesandbox 上确认它可以使用或不使用styled 添加沙盒codesandbox.io/s/gritty-styled-grid-7l04g Arg,谢谢。它是内部网格,而不是外部网格。 【参考方案1】:

您的Griddirection 属性仅在container 属性设置为true 时有效,因此在您的内部Grid 中添加缺少的container 属性。在内部,一个容器Grid的显示设置为flex,而direction映射到flex-direction,如果布局不是flex,flex-direction是没有意义的:

<Grid container direction='column'

【讨论】:

【参考方案2】:

只是补充一下 NearHuscarl 提到的内容,这是您缺少 container 道具的地方。


<Box m=1 overflow="auto">
  <SettingsGrid
      container
      direction="row"
      justifyContent="center"
  >
      <Grid
          container  <<<------------------ you are missing this 
          direction="column"
          style= minWidth: '35em', maxWidth: '60em' 
      >
          <!-- ... -->
      </Grid>
    </SettingsGrid>
</Box>

【讨论】:

谢谢,终于注意到了。

以上是关于MUI v5:失败的道具类型:`Grid`的道具`direction`只能与`container`道具一起使用的主要内容,如果未能解决你的问题,请参考以下文章

MUI v5:我是不是需要安装 @emotion/react 或 @emotion/styled 才能使用 sx 道具?

react-navigation v5 中的 Typescript StackNavigatonProps 和 Screen 道具

道具类型失败:“object”类型的道具“defaultValue”无效

在 React.js 中进行道具验证时道具类型失败

警告:失败的道具类型:提供给“Carousel”的“对象”类型的无效道具`数据`,预期`数组`

道具类型失败:提供给“TextInput”React Native 的“对象”类型的无效道具“值”