【问题标题】:React - How do you get the top position of a styled component?React - 如何获得样式组件的顶部位置?
【发布时间】:2018-08-24 13:38:27
【问题描述】:

当您不了解 React 方式时,曾经简单的事情变得相当复杂。

我正在尝试创建一个组件,使其在到达页面顶部时起到粘性页眉或页脚的作用。

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

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

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

但是,对于如何获得样式组件的滚动顶部位置,我遇到了困难。所以假设我有一个名为Container 的样式组件,它输出了一个表单,我通常只添加一个数据属性并执行以下操作:

const container = document.getElementbyTag("data-sticky-container")
const position = container.offsetTop 

我将如何在 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);
  }

【问题讨论】:

    标签: javascript css reactjs


    【解决方案1】:

    在反应中,您可以为您的组件使用参考: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} />;
      }
    }
    

    现在您可以通过this.myRef.current.offsetToponScroll 函数中访问容器offsetTop,就像在getOffset 中一样

    【讨论】:

    • 你知道为什么 offsetTop 是未定义的吗?
    • 对不起 - 你需要做this.myRef.current.offsetTop
    • 我现在正在对当前进行 undefine。我会用更多信息更新我的答案。感谢您迄今为止的帮助
    • 我认为你需要像这样在构造函数中绑定onScrollthis.onScroll = this.onScroll.bind(this);
    • 没问题 - 顺便说一句:如果你使用像 onScroll = () =&gt; {} 这样的箭头函数,你不必绑定函数。更多信息:reactarmory.com/answers/when-to-use-arrow-functions
    【解决方案2】:

    另一种选择是使用innerRef。这可能会更好,因为它会给你一个对 DOM 节点的引用,而不仅仅是一个包装器。看到这个answer

    然后,您将可以更直接地访问 scrollTop 等属性。

    ref 不同,innerRef 使用回调:

    在你的情况下,它看起来像:

    class MyComponent extends React.Component {
    
      constructor(props) {
        super(props);
        this.myRef;
      }
    
      getOffset = () => {
        console.log(this.myRef.offsetTop);  
      }
    
      render() {
        return <Container
            innerRef={element => this.textInput = element}
            onClick={this.getOffset} />;
      }
    }
    

    【讨论】:

      【解决方案3】:

      您可以添加 ref 到你想要一个 offsetTop 的组件。这个 ref 将包含该组件的所有计算的 css 值。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-11-15
        • 2018-08-26
        • 2022-10-16
        • 2018-03-20
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多