javascript - 如何使用 TypeScript 获取 React Child 的 offsetTop

标签 javascript reactjs typescript dom typescript-typings

如何使用 Typescript 获取 React 子元素 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'
  • 将 child 转换到 ReactElement<any>

有什么想法吗?

最佳答案

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

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

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

关于javascript - 如何使用 TypeScript 获取 React Child 的 offsetTop,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53120466/

相关文章:

javascript - 如何使用 PHP 在电子邮件中以 HTML/文本格式发送 Javascript

javascript - 简化关联数组

Javascript:如何从子窗口刷新父窗口

node.js - 是否可以使用 JSX 进行 React 工作,无需 Node 服务器并使用 create-react-app

javascript - 即使未调用线路,Angular2 路由器也会执行

javascript - 尝试为 next.js 项目设置 ava 单元测试,但出现两个与设置相关的错误

javascript - 简单的 React 计数器不起作用,console.log 也不能使用State 变量吗?

javascript - reactjs 中的 this.state.todolist.push() 返回一个数字?

javascript - 在 TypeScript 中缩小过滤器和映射链中对象属性的类型

unit-testing - TestBed configureTestingModule 在一个模块中定义所有 spec.ts 通用的导入、声明、提供程序和管道 - 模式