如何使用TypeScript获取React子代的offsetTop

时间:2018-11-02 14:29:57

标签: javascript reactjs typescript dom typescript-typings

如何使用Typescript获取React子元素offsetTop?

这是我的组件:

toString

我已经尝试过:

  • 使用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
  • 将孩子cast到Property 'getBoundingClientRect' does not exist on type 'ReactChild'. Property 'getBoundingClientRect' does not exist on type 'string'

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

1。尝试将引用发送到父组件

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

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