如何结合styled-components使用Material System并消除React属性警告?
解决React警告:不识别的Material System Props传递到DOM元素
这个警告我之前也碰到过,核心原因很简单:你把所有props(包括Material System的样式props,比如maxWidth)都直接传给了Grid组件,而Grid会把它不认识的props转发到底层的DOM元素上,React就会抛出这个警告。
下面给你两种可行的解决方法,按需选择就行:
方法一:手动解构分离样式props和Grid原生props
你可以明确把Material System用到的props解构出来,只把Grid真正需要的props传进去:
import React from 'react' import Grid from '@material-ui/core/Grid' import { spacing, sizing, color, flexbox, display } from '@material-ui/system' import styled from 'styled-components' const Row = styled(({ maxWidth, width, spacing, ...restProps }) => <Grid container {...restProps} />)` ${spacing} ${sizing} ${color} ${flexbox} ${display} ` export default Row
这种方式直观易懂,但如果用到的样式props比较多,手动解构会有点繁琐。
方法二:用Material-UI自带的props过滤工具(更优雅)
Material-UI专门提供了propsFilter工具,能自动识别并过滤掉那些样式相关的props,不用你手动一个个解构:
首先导入这个工具:
import { spacing, sizing, color, flexbox, display, propsFilter } from '@material-ui/system'
然后修改你的组件代码:
const Row = styled(props => { // 过滤掉样式props,只保留Grid能识别的props const gridProps = propsFilter(props, { spacing, sizing, color, flexbox, display }) return <Grid container {...gridProps} /> })` ${spacing} ${sizing} ${color} ${flexbox} ${display} `
propsFilter会自动匹配你用到的Material System模块对应的props,把它们从传给Grid的props里移除,这样就不会有不认识的props跑到DOM元素上了,完美解决警告。
额外小建议(针对Material-UI v5+)
如果你的项目用的是Material-UI v5及以上版本,其实可以直接用Material-UI官方的styled工具(它本身基于styled-components),它会自动处理props过滤,写法更简洁:
import { styled } from '@material-ui/core/styles' import Grid from '@material-ui/core/Grid' import { spacing, sizing, color, flexbox, display } from '@material-ui/system' const Row = styled(Grid)(({ theme }) => ({ ...spacing(theme), ...sizing(theme), ...color(theme), ...flexbox(theme), ...display(theme), })) // 默认给Row加上container属性,不用每次写 Row.defaultProps = { container: true, } export default Row
这种方式更贴合Material-UI v5的生态,也能从根源避免props传递的问题。
内容的提问来源于stack exchange,提问作者Daniel Pôrto Nuñez
相关产品推荐
相关产品推荐

