【问题标题】:React: Access child element with findDOMNode throws errorReact:使用 findDOMNode 访问子元素会引发错误
【发布时间】:2015-11-05 03:37:01
【问题描述】:

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

componentDidUpdate 我想更改样式属性。

似乎容器应该能够处理这个问题,而不是每个孩子自己处理。

问题,react 在尝试获取子节点的 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>)
  }
})

【问题讨论】:

标签: reactjs


【解决方案1】:

在使用 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

【讨论】:

  • 嗯。这是一个粗略的例子:我的父母有 10 个孩子,一次只有 1 个是“活跃的”。让父母“显示:阻止”在活动的一个上,让其他人显示:无;
猜你喜欢
  • 2018-10-15
  • 1970-01-01
  • 2015-11-18
  • 1970-01-01
  • 2022-07-21
  • 2018-12-09
  • 1970-01-01
  • 2017-10-30
  • 2017-12-09
相关资源
最近更新 更多