以下是我的源代码,我试图在其中获取组件的引用,并检查单击是否发生在组件外部,但由于未定义而来,我收到错误消息。让我知道我在这里做错了。
代码-
// @flow
import { PureComponent, createRef } from 'react';
import type { Props, State } from 'types';
class MyComponent extends PureComponent<Props, State> {
static defaultProps = {
myComponentBody: ''
};
state: State = {
showMyComponent: false,
};
wrapperRef: { current: null | HTMLDivElement } = createRef();
componentDidMount() {
document.addEventListener('mousedown', this.handleClickOutside);
}
componentWillUnmount() {
document.removeEventListener('mousedown', this.handleClickOutside);
}
handleClickOutside(e: SyntheticEvent<>) {
console.log(`Inside --->`); // This function is triggering
console.log(this); // I am getting #document whole html
console.log(this.wrapperRef); // undefined
console.log(wrapperRef); // Uncaught ReferenceError: wrapperRef is not defined
if (this.wrapperRef && !this.wrapperRef.contains(e.target)) {
this.setState({
showMyComponent: false,
});
}
}
handleClick(e: SyntheticEvent<>) {
this.setState({
showMyComponent: true,
});
}
render() {
const { myComponentBody } = this.props;
return (
<div onClick={e => this.handleClick(e)} ref={this.wrapperRef}>
{this.props.children}
{this.state.showMyComponent && (
<div>
<div>{myComponentBody}</div>
</div>
)}
</div>
);
}
}
答案 0 :(得分:1)
由于您要访问此(这是当前课程的上下文)。
有几种方法。
1。将您的handleClickOutside
绑定到构造函数中
constructor(props){
super(props);
this.handleClickOutside = this.handleClickOutside.bind(this);
}
2。将handleClickOutside
转换为箭头功能。
handleClickOutside = (e: SyntheticEvent<>) => {
console.log(`Inside --->`); // This function is triggering
console.log(this); // I am getting #document whole html
console.log(this.wrapperRef); // undefined
console.log(wrapperRef); // Uncaught ReferenceError: wrapperRef is not defined
if (this.wrapperRef && !this.wrapperRef.contains(e.target)) {
this.setState({
showMyComponent: false,
});
}
}
3。或者,您也可以在点击事件中将其绑定
return (
<div onClick={this.handleClick.bind(this)} ref={this.wrapperRef}>
{this.props.children}
{this.state.showMyComponent && (
<div>
<div>{myComponentBody}</div>
</div>
)}
</div>
);