React - 如何获得样式组件的顶部位置?

Max*_*ynn 2 javascript css reactjs

当你不知道React的方式时,过去很简单的东西会非常复杂.

我正在尝试创建一个组件,当它到达页面顶部时就像一个粘性页眉或页脚.

目前我非常满足于添加以下内容:

  componentDidMount() {
    window.addEventListener('scroll', this.onScroll, false);
  }

  componentWillUnmount() {
    window.removeEventListener('scroll', this.onScroll, false);
  }
Run Code Online (Sandbox Code Playgroud)

然而,我已经找到了如何获得样式组件的滚动顶部位置.所以假设我有一个调用的样式组件,Container并输出一个表单我通常只是添加一个数据属性,并执行如下所示的操作:

const container = document.getElementbyTag("data-sticky-container")
const position = container.offsetTop 
Run Code Online (Sandbox Code Playgroud)

我将如何在React中执行此操作?


更新

现在用ref.我遇到了一个没有定义电流的问题:

  constructor(props) {
    super(props);
    this.optionBox = React.createRef();
  }

  componentDidMount() {
    window.addEventListener('scroll', this.onScroll, false);
  }

  componentWillUnmount() {
    window.removeEventListener('scroll', this.onScroll, false);
  }

  onScroll() {
    console.log(this.optionBox.current.offsetTop);
  }
Run Code Online (Sandbox Code Playgroud)

Lau*_*ück 7

在反应中,您将使用组件的参考:https://reactjs.org/docs/refs-and-the-dom.html

你会有这样的事情:

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.myRef = React.createRef();
  }

  getOffset = () => {
    console.log(this.myRef.current.offsetTop);  
  }
  render() {
    return <Container ref={this.myRef} onClick={this.getOffset} />;
  }
}
Run Code Online (Sandbox Code Playgroud)

现在,您可以通过函数this.myRef.current.offsetTop内部访问容器offsetToponScrollgetOffset

  • 你知道为什么 offsetTop 会是 undefined 吗? (3认同)