div ID在父组件中的滚动位置

时间:2018-08-09 07:08:25

标签: javascript reactjs

使用ReactJS和GatsbyJS(v2),我有一个troysArray[i][j]组件,它在父header组件的fixed上位于div id="outerContainer"上。

要在layout以下的滚动位置上切换类,通常使用100px

但是,由于主体类的样式为window.scrollY < 100overflow:hidden的样式为outerContainer,因此overflow: scroll的滚动位置不会改变。

如何在引用父级window滚动位置的同时从子级组件定义outerContainer.scrollY < 100

Layout.js

outerContainer

Header.js

const Layout = ({ children }) => (
  <div>
    <div id="outerContainer" ref={el => (this.outerContainer = el)}>
      <div className="content">{children}</div>
    </div>
    <Header />
  </div>
);

我的第一个想法是我应该在class Header extends React.Component { constructor(props) { super(props); this.state = { navScrolled: true }; this.onScroll = this.onScroll.bind(this); } componentDidMount() { document.addEventListener('scroll', () => { const navScrolled = outerContainer.scrollY < 100; if (navScrolled !== this.state.navScrolled) { this.onScroll(navScrolled); } }); } componentWillUnmount() {...} ... } 中执行功能,并使用layout.js传递状态。这是最好的选择,还是还有另一种方法可以激发props中的所有内容?

1 个答案:

答案 0 :(得分:1)

您首先想到的是正确的,父类是onScroll回调的正确位置,因为滚动位置是整个布局的属性,而不是仅使用它的标头的属性。

此外,通过将onScroll保留在父类中,即使在开发期间它可能成长为单独的类,您也可以将其传递给externalContainer。