TypeScript环境下为styled-components包裹的Material-UI Button传递Props出现警告的原因及解决方法
问题分析与解决方案
为什么会出现警告?
你遇到的这个警告,核心原因是:你自定义的primary属性被styled-components默认转发给了底层的Material-UI Button组件,但MUI的Button根本不接受primary这个props。
styled-components的默认行为是把所有传入Styled组件的props都传递给被包裹的基础组件(这里就是MUI Button),而你的primary是用来控制样式的自定义属性,并不是MUI Button的合法属性,React检测到DOM元素收到了未知属性,就会抛出警告。
两种解决办法
方法1:用shouldForwardProp过滤自定义props
styled-components提供了shouldForwardProp配置项,可以精准控制哪些props需要转发给基础组件。我们可以用它阻止primary被传递给MUI Button:
import React from 'react'; import styled from 'styled-components'; import Button, {ButtonProps} from "@material-ui/core/Button"; type StyledButtonProps = ButtonProps & { primary?: boolean } const styledButton = styled(Button).withConfig({ // 只转发除了primary之外的props shouldForwardProp: (prop) => prop !== 'primary' })` background-color: ${(props: StyledButtonProps) => props.primary ? "palevioletred" : "white"}; box-shadow: 0 4px 6px rgba(50, 50, 93, 0.11), 0 1px 3px rgba(0, 0, 0, 0.08); padding: 7px 14px; &:hover { background-color: aqua; } & .MuiButton-label { color: #070303; } ` as React.ComponentType<StyledButtonProps> export default styledButton;
这样修改后,primary就只会被用在样式逻辑里,不会被传递给底层组件,警告自然就消失了。
方法2:重命名自定义props避免冲突
如果你觉得配置shouldForwardProp有点麻烦,也可以直接把自定义的primary改成一个不会和MUI props冲突的名字,比如isPrimary:
import React from 'react'; import styled from 'styled-components'; import Button, {ButtonProps} from "@material-ui/core/Button"; // 修改类型定义里的属性名 type StyledButtonProps = ButtonProps & { isPrimary?: boolean } const styledButton = styled(Button)` // 这里也同步改成isPrimary background-color: ${(props: StyledButtonProps) => props.isPrimary ? "palevioletred" : "white"}; box-shadow: 0 4px 6px rgba(50, 50, 93, 0.11), 0 1px 3px rgba(0, 0, 0, 0.08); padding: 7px 14px; &:hover { background-color: aqua; } & .MuiButton-label { color: #070303; } ` as React.ComponentType<StyledButtonProps> export default styledButton;
使用组件的时候也要对应修改:
<StyledButton isPrimary={true}>Styled Button</StyledButton>
这种方式更直观,从根源上避免了命名冲突,同样能解决警告问题。
内容的提问来源于stack exchange,提问作者Krzysztof Michalski
相关产品推荐
相关产品推荐

