我正在将此类模块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。
您不是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
方法。