2015-11-05 86 views
2

我有一个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>) 
    } 
}) 
+0

的jsfiddle再现https://jsfiddle.net/69z2wepo/19983/ –

+0

您遇到这种情况:https://github.com/facebook/react/issues/4244 – Errorpro

回答

0

当您使用React时,您尝试执行的操作不是建议的做法。请勿自行修改DOM,请使用stateprops

儿童成分:

var ChildrenA = React.createClass({ 
    render: function() { 
     return <div style={{color: this.props.color}}>Hello A</div>; 
    } 
}); 

应用:

var App = React.createClass({ 
    render: function() { 
     return (<div> 
      <div>Hello {this.props.name}</div> 
      <div> 
      <Container/> 
      </div> 
     </div>); 
    } 
}); 

集装箱:

var Container = React.createClass({ 
    getInitialState: function(){ 
     return {color: "red"} 
    }, 
    toggle: function(){ 
     this.setState({ 
     color: this.state.color == "red" ? "blue" : "red" 
     }) 
    }, 
    render: function() { 
     return (<div onClick={this.toggle}> 
      <ChildrenA color={this.state.color}/> 
      <ChildrenB/> 
     </div>); 
    } 
}); 

的jsfiddle:https://jsfiddle.net/3m8wLcgk/

你可能要检查这个OU T:Thinking in React

+0

嗯。继承人一个粗略的例子:我的父母包含10个孩子,一次只有1个“活跃”。似乎是合理的,让父母的“显示器:块”处于活动状态,并让其他人显示:无; –