2016-08-16 77 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

只需将您的道具从“关闭”重新命名为“数据关闭”即可。而已。