无法将React.RefObject与打字稿一起使用

问题描述 投票:1回答:1

我正在将此类模块example移植到打字稿,但是我无法正确设置对象引用的定义。

我将参考持有人定义为:

private wrapperRef:React.RefObject<HTMLDivElement>

原始处理程序必须更改,因此它使用当前属性,具有此:

if (this.wrapperRef.current && !this.wrapperRef.current.contains(event.target)) {
  alert('You clicked outside of me!');
}

但是this.wrapperRef.current总是undefined

我做错了什么?

这里是我的sandbox

javascript reactjs typescript
1个回答
1
投票

您不是creating or setting your ref properly。在类组件中,使用React.createRef()

创建引用
constructor(props) {
  super(props)
  this.wrapperRef = React.createRef<HTMLDivElement>()
}

然后通过将其值直接传递到某个元素的ref属性来分配其值。

render() {
  return <div ref={this.wrapperRef}>{this.props.children}</div>;
}

现在,它应该在第一次渲染后自动设置this.wrapperRef.current。您根本不需要setWrapperRef方法。

Sandbox

© www.soinside.com 2019 - 2024. All rights reserved.