React:使用findDOMNode访问子元素会引发错误

时间:2015-11-05 03:37:01

标签: reactjs

我有一个Container组件,它有几个孩子。

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>)
  }
})

1 个答案:

答案 0 :(得分: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/

您可能需要查看此内容:Thinking in React