如何解决React出现react/jsx-no-duplicate-props重复Props警告问题
问题原因
你触发react/jsx-no-duplicate-props警告的核心原因是:你在<MuiDialogTitle>组件上手动声明了disableTypography、className两个属性,同时展开的...other参数里也包含了这两个同名属性,同一组件上出现了重复的props名称。
解决方法
方案1:调整props优先级(推荐,适配大多数场景)
把手动声明的属性放到...other展开之后,手动属性会覆盖other里的同名属性,不会出现重复冲突,同时支持外部传入的其他属性正常透传:
const DialogTitle = withStyles(styles)((props) => { const { children, classes, onClose, ...other } = props; return ( <MuiDialogTitle {...other} disableTypography className={classes.root}> <Typography variant="h6">{children}</Typography> {onClose ? ( <IconButton aria-label="close" className={classes.closeButton} onClick={onClose}> <CloseIcon /> </IconButton> ) : null} </MuiDialogTitle> ); });
方案2:过滤重复属性
如果你要强制使用你声明的disableTypography和className,不允许外部传入的属性覆盖,就直接把这两个属性从other里过滤掉:
const DialogTitle = withStyles(styles)((props) => { // 解构后丢弃不需要透传的两个属性,避免重复传递 const { children, classes, onClose, disableTypography: _, className: __, ...other } = props; return ( <MuiDialogTitle disableTypography className={classes.root} {...other}> <Typography variant="h6">{children}</Typography> {onClose ? ( <IconButton aria-label="close" className={classes.closeButton} onClick={onClose}> <CloseIcon /> </IconButton> ) : null} </MuiDialogTitle> ); });
内容的提问来源于stack exchange,提问作者chelsey lee
相关产品推荐
相关产品推荐

