如何使用 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/