React/Flux 实施技术不清楚 parent 组件何时需要在 child 组件上拉线

React/Flux implementation technique is unclear for when a parent component needs to pull strings on child component

我遇到了一个不太人为的情况,我在使用 React 最佳实践实施它时遇到了麻烦。特别是它会产生此错误:

Uncaught Error: Invariant Violation: setProps(...): You called setProps on a component with a parent. This is an anti-pattern since props will get reactively updated when rendered. Instead, change the owner's render method to pass the correct value as props to the component where it is created.

情况是这样的。 parent 包含一个 child 组件。 parent 具有 UI 的事件处理程序,为了使行为起作用,child 组件内部的某些内容需要通过 CSS 更改来呈现其 HTML高度样式。这就是问题所在,通常信息会向上流动或保持不变,但在这里我需要在 child.

中更改一些内容

Parent 组件 (Widget) 呈现:

<div class="Widget">
  <div class="WidgetGrabBar" onMouseDown={this.handleMouseDown}>
  <WidgetDetails heightProp={this.props.detailsHeight} />
</div>

在 Widget 的其他地方我有

componentDidMount: function() { 
  document.addEventListener('mousemove', this.handleMouseMove);
  document.addEventListener('mouseup', this.handleMouseUp);
},
componentDidUnmount: function() {
  document.removeEventListener('mousemove', this.handleMouseMove);
  document.removeEventListener('mouseup', this.handleMouseUp);
},      

<...>

handleMouseDown: function(e) {                                                   
  e.preventDefault(); 
  this.props.actuallyDragging = true;                                                   
},
handleMouseUp: function(e) {
  this.props.actuallyDragging = false;
},       
handleMouseMove: function(e) {
  e.preventDefault();
  if (this.props.actuallyDragging) {
    // update the prop! I need to send an urgent package of information to my child!! jQuery or findDOMElement() followed by DOM traversal is forbidden!!!
    this.setProps({
      detailsHeight: this.props.detailsHeight + e.deltaY
    });
  }                                                                                        
},                                                                                    

WidgetDetails' render() 渲染如下:

<div class="WidgetDetails" style={height: this.props.heightProp}>
   {detail_items_move_along_nothing_to_see_here}
</div>

我认为推出 jQuery 以利用其 style 属性将 .WidgetDetails 抓取到 fiddle 是 错误的 事情,non-React 的方法。真实的anti-pattern.

但现在我被告知我无法更改我的道具。或者我必须扔掉包括洗澡水在内的所有东西才能拥有新的道具。我没有那样做;我的道具包含详细项目的 内容 。制作另一个全新的副本可能很昂贵。

我正在尝试让 React 参与此渲染工作以放入新的高度。我应该怎么做呢?这个错误基本上是在强制 Props 现在应该是不可变的吗?错误告诉我,我必须在组件链的更上层涉及这个高度。可以想象,我可以通过上面的回调来做到这一点,但这感觉很不对。我需要向下传递信息,而不是向上传递信息。

也许我应该使用 state。但是更改 state 会强制 Widget,parent 组件进行渲染。那不是我想要的。 DOM中只有一处需要re-render,即child组件的div的style属性

有两种方法。

  1. 调用 parent 上的处理程序。然后通过道具将新道具传递给 child。如果我没记错的话,这就是 react hello world 教程所采用的方法。
  2. 通过 setState 在视图中改变状态。

在您的情况下,方法 2 似乎确实很有意义。您基本上是在尝试跟踪视图数据。

永远不要直接更新状态。使用设置状态。 reacts virtual dom 的全部意义在于它针对虚假更新进行了优化,所以你会没事的。还有生命周期方法 componentShouldUpdate 以防你想要更好的控制。

为了完整起见,我应该补充一点,还有第三种使用全局存储的方法。这就是反应通量所增加的。但同样,在你的情况下,这可能已经结束了。