我有一个Container
组件,它会得到一些孩子。反应:访问子元素与findDOMNode抛出错误
on componentDidUpdate
我想更改样式属性。
看起来像容器应该能够处理这个,而不是每个孩子处理它自己。
问题,当试图获取孩子的Dom节点时反应会引发错误。
var childA = this.props.children[0];
React.findDOMNode(childA);
=> Uncaught Error: Invariant Violation: Element appears to be neither ReactComponent nor DOMNode (keys:)
编辑:这^^^是错误的方式写反应!
如果你的孩子需要做点什么,你应该总是试着从顶端去传递它。
可以说你有3种颜色:green,red,blue
并且你希望你的孩子被这样染色,但也许他们经常改变顺序。将它传递下去
Parent = React.createClass({
renderChildren: function(){
var colors = ["red", "blue", "green"]
return React.Children.map(this.props,children, function(child, index){
// this returns a legit clone, adding one extra prop.
return React.cloneElement(child, {color: colors[index]});
})
},
render: function(){
return (
<div>{this.renderChildren()}</div>
)
}
})
Child = React.createClass({
render: function(){
return (<div style={{background: this.props.color}}>{'YOLO'}</div>)
}
})
的jsfiddle再现https://jsfiddle.net/69z2wepo/19983/ –
您遇到这种情况:https://github.com/facebook/react/issues/4244 – Errorpro