所以我有一个 <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>
与此同时,组件是否“应该”了解窗口? <Layout>
目前是我的最高水平,所以我认为那里很好,但不确定 child 等。
基本上不确定什么是连接全局窗口大小和组件位置方面的最佳方法。
最佳答案
这个方法并不完美,但对我来说效果很好。
我的代码有根组件 Application
,如果你正在使用 react-router
你可能也有一个,否则很容易添加它。
我还有用于管理屏幕分辨率或方向等窗口属性的缩减器和操作。我们称它们为 windowReducer
和 windowActions
。
在根组件中,我用类似的东西注册了事件处理程序:
componentDidMount() {
window.addEventListener('resize', this.onWindowResolutionChange, false);
}
onWindowResolutionChange() {
windowActions.onResolutionChange({
width: window.innerWidth,
height: window.innerHeight
});
}
作为其他 redux 操作 onResolutionChange
将操作分派(dispatch)到 windowReducer
并在其中设置新的窗口宽度和高度。
因此,要将它们放入您的组件中,您只需将它们作为其他 Prop 从容器的 state
传递即可。
这种方法中最糟糕的是 state
更改过于频繁,这会导致组件的额外重新渲染。通常你使用像 debounce 这样的函数避免它。如果你们中的一个组件需要立即更改和其他去抖动,您可能会(像我一样)以两种不同的操作结束,将不同的值设置为状态(width
和 debouncedWidth
).
关于javascript - 有没有更好的方法来处理 React/Redux 中的窗口属性和子组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36728062/