2016-08-16 83 views
3

當我從事兒童工作的道具未知道具警告

Unknown prop接近on <h3> tag. Remove this prop from the element.我發現了一個錯誤。

我創建了一個母塊:

var Block = React.createClass({ 
    getInitialState: function() { 
    return {open: true} 
    }, 

    close: function() { 
    this.setState({open: false}); 
    }, 

    render: function() { 
    var childrenWithProps = React.Children.map(this.props.children,  function(child) { 
     return React.cloneElement(child, { 
      close: this.close 
     }) 
    }.bind(this)); 

    return (
     <div> 
      {childrenWithProps} 
     </div> 
    ) 
} 
}); 

而在另一個組件使用它:

var Elm = React.createClass({ 
render: function() { 
    return (
     <Block> 
      <h3>Hi</h3> 
      <button type="button" onClick={this.props.close}>Close</button> 
     </Block> 
    ) 
} 
}); 

我知道這是因爲<h3>沒有close,但button有它。

我該如何解決?

謝謝。

回答

1

你得到這個錯誤,因爲你映射React.Children在內部迭代的Block成分的兒童(包括<h3>標籤),然後close財產分配給它。

Why you should pay attention to this warning.

但是請注意,無論是<h3>也不<button>close財產,什麼<button>反而是作爲onClick屬性傳遞的this.prop.close值。

你可以做的,然後就是設置一些屬性,作爲一個標誌,你Block組件,因此您可以像一個「關閉元素」對待它,姑且稱之爲closeEmitter

Block.render()

var self = this; 

var childrenWithProps = React.Children.map(function(child) { 
    let extension = child.props.closeEmitter ? { onClick: self.close } : {} 
    React.cloneElement(child, extension); 
}); 

return <div> 
    { childrenWithProps } 
</div> 

Elm.js

var Elm = React.createClass({ 
    render: function() { 
    return <Block> 
     <h3>Hi</h3> 
     <button type="button" closeEmitter={ true }>Close</button> 
    </Block> 
    } 
}); 
+1

謝謝。我想創建一個我可以在任何地方使用的Popup組件。它可以有很多孩子。孩子們可以關閉它。 – Fijir

+1

然後你應該照我說的去做:在'Block'定義中定義'

+1

的下面。是的,但'button'就是例子。我可以有一個應該關閉Popup的元素。例如,一些鏈接「關閉彈出」或一些行動後... – Fijir

4

只需將您的道具從「關閉」重新命名爲「數據關閉」即可。而已。