1. 程式人生 > >warning: React does not recognize the xxx prop on a DOM element

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

ref urn ret con pro dom元素 bject 解決 tps

這是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

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