【问题标题】:How to get offsetTop of a React Child with TypeScript如何使用 TypeScript 获取 React Child 的 offsetTop
【发布时间】:2019-04-06 19:26:24
【问题描述】:

如何使用 Typescript 获得 React children offsetTop?

这是我的组件:

export default class FadeIn extends Component {
  private onScroll = () => {
    React.Children.forEach(this.props.children, child => {
      // Get the child's offsetTop here and do stuff with
    })
  }

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

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

  public render() {
    return this.props.children
  }
}

我已经尝试过:

  • 使用ReactDOM.findDOMNode(child) 但我得到Argument of type 'ReactChild' is not assignable to parameter of type 'ReactInstance'. Type 'string' is not assignable to type 'ReactInstance'
  • 使用getBoundingClientRect 但我得到Property 'getBoundingClientRect' does not exist on type 'ReactChild'. Property 'getBoundingClientRect' does not exist on type 'string'
  • 将孩子投给ReactElement<any>

有什么想法吗?

【问题讨论】:

    标签: javascript reactjs typescript dom typescript-typings


    【解决方案1】:

    1.尝试将 ref 发送到父组件

    2.将引用保存到变量或状态中

    3.然后在componentDidMount方法中,可以通过getBoundingClientRect获取子组件的高度。

    【讨论】:

      猜你喜欢
      • 2020-05-01
      • 2015-12-16
      • 2020-03-25
      • 2010-11-05
      • 2013-03-21
      • 2018-02-12
      • 2019-12-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多