javascript - 在 React 中没有在函数内部获取 ref
问题描述
以下是我的源代码,我在其中尝试获取组件的引用并检查单击是否发生在组件外部,但由于未定义而出现错误。让我知道我在这里做错了什么。
代码 -
// @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>
);
}
}
解决方案
因为你想访问this这是你当前类的上下文。
有几种方法可以解决这个问题。
handleClickOutside
1.在构造函数中绑定你的
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>
);
推荐阅读
- php - 如何创建一个反函数以雄辩地保存在我的 mysql 中?
- multithreading - 解析文件时减少执行时间
- python - 需要同时使用 seek()、tell()、next() 和 readline() 函数
- c - C如何将指针传递到文件中的位置以进行读取
- google-fabric - 如何删除特定设备?
- c# - 为什么 request.Headers.Add("Cookie", "...") 没有效果?
- azure-devops - 在 vsts 发布期间更新文本文件
- netty - 令人困惑的netty IllegalAccessError 4.1.5.Final
- symfony - KnpSnappyBundle 和 Symfony 3.4:图像和/或 css 导致超时
- c# - 从选定的链接或按钮获取文本