是否有更好的方法来处理窗口属性和& React / Redux中的子组件?

时间:2016-04-19 19:46:43

标签: javascript reactjs react-redux

所以我有一个<Layout>组件。根据页面,它加载不同的子组件。在那些,他们可能有标签,他们可能没有。

这改变了我想滚动的方式,因此也改变了滚动的标记。

我基本上最终确保每个子组件都有<div id="scroll-container">

之类的元素

然后在我的<Layout>组件中我做了这个:

componentDidMount() {

  this._updateHeight();
  window.addEventListener('resize', this._updateHeight, false);
},

componentDidUpdate() {
  this._updateHeight();
},

_updateHeight() {
  var container = document.getElementById('scroll-container');

  if (container ) {
    let height = window.innerHeight - container.getBoundingClientRect().top;
    container.style.height = height + 'px';
  }
},

我知道有getBoundintClientRec之类的帮手,我将在稍后使用。现在我只是想知道一般的流程。

我在想我可以制作一个scroll-container组件,无论我需要哪个组件,但是我需要总是做一些像

这样的事情。
<ScrollContainer {...this.props}>
  <ChildIHadThereAnyway>
</ScrollContainer>

同时是一个组件&#34;假设&#34;了解窗户? <Layout>目前是我的最高级别,所以我认为那里很好,但对儿童等不确定。

基本上不确定什么是最适合将全局窗口大小与组件位置的方面连接。

1 个答案:

答案 0 :(得分:0)

这种方法并不完美,但对我来说效果很好。

我的代码有根组件Application,如果你使用react-router,你可能也有一个,否则很容易添加它。

我还有用于管理窗口属性(如屏幕分辨率或方向)的reducer和操作。让我们称他们为windowReducerwindowActions

在根组件中,我使用类似的东西注册事件处理程序:

componentDidMount() {
  window.addEventListener('resize', this.onWindowResolutionChange, false);
}

onWindowResolutionChange() {
  windowActions.onResolutionChange({
    width: window.innerWidth,
    height: window.innerHeight
  });
}

其他redux操作onResolutionChange会将操作发送到windowReducer,并设置新的窗口宽度和高度。

因此,要将它们放入您的组件中,您只需将它们从容器的state传递给其他道具。

这种方法中最糟糕的是state变化太频繁导致组件的额外重新渲染。通常你使用像debounce这样的函数来避免它。如果你的某个组件需要立即更改而其他组件需要立即更改,那么您可能会以两种不同的操作结束(就像我一样)将不同的值设置为状态(widthdebouncedWidth)。