当用户单击元素外部时,我尝试制作可切换内容,但出现了 this.node 未定义错误?
handleOutsideClick(e) {
// ignore clicks on the component itself
if (this.node.contains(e.target)) {
return;
}
this.handleClick();
}
render() {
return (
<div ref={node => { this.node = node; }}>
<button onClick={this.handleClick}>Button handler</button>
{this.state.visibleContent && <div>Toggle content</div>}
</div>
);
}
代码https://codesandbox.io/s/v38q4zrq7
在渲染方法中我使用了 ref={node => { this.node = node; }}
为什么它仍然是未定义的?这是一个使用完全相同技术的工作示例 https://codepen.io/graubnla/pen/EgdgZm
最佳答案
您的函数handleOutsideClick
超出了范围。如果你使用babel,可以直接将其变成箭头函数
handleOutsideClick = (e) => {
// ignore clicks on the component itself
if (this.node.contains(e.target)) {
return;
}
this.handleClick();
}
或者如果这不是一个选项,请将其绑定(bind)到构造函数中
constructor() {
super()
this.handleClick = this.handleClick.bind(this)
}
关于javascript - ref 不是使用 react 中的箭头函数定义的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49527412/