warning: React does not recognize the xxx prop on a DOM element

本文解析了React中关于非标准DOM属性的警告,详细解释了如何避免将无效属性传递给DOM元素,提供了代码示例及解决方案,如使用rest参数和删除属性的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这是React不能识别dom元素上的非标准attribute报出的警告,最终的渲染结果中React会移除这些非标准的attribute。

通常{...this.props}和cloneElement(element, this.props)这两种写法,会将父级别无用的attribute传递到子级的dom元素上。

例如:

function MyDiv(props) {
  if (props.layout === 'horizontal') {
    // BAD! Because you know for sure "layout" is not a prop that <div> understands.
    return <div {...props} style={getHorizontalStyle()} />
  } else {
    // BAD! Because you know for sure "layout" is not a prop that <div> understands.
    return <div {...props} style={getVerticalStyle()} />
  }
}

可以使用rest参数接收,删除等方法来解决:

const { layout, ...rest } = props
//或者
const divProps = Object.assign({}, props);
delete divProps.layout;

具体可参考:React官方文档 Unknown Prop Warning

转载于:https://www.cnblogs.com/mengff/p/9822266.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值