【发布时间】:2020-01-07 01:55:45
【问题描述】:
我有这个点击处理程序:
clickHandler = event => {
if (this.node.contains(event.target)) {
console.log("clicked inside");
return;
}
console.log("clicked outside");
};
我的 List 组件是这样定义的;
const List = styled.ul`
margin: 0;
padding: 5px 0;
list-style: none;
border-top: 1px solid #789;
color: black;
font-weight: 500;
`;
然后在我的渲染函数中我有这个;
<List ref={node => (this.node = node)} key={index}>
当我的点击处理程序被执行时,我得到以下错误:
TypeError: _this.node.contains 不是函数
如果我控制台记录 this.node 我可以看到它是一个样式组件,但它没有 ref 也没有 innerRef 属性,所以我看不到如何访问底层节点元素以便我可以使用.contains()
这就是我在 package.json 中的内容:
"styled-components": "^3.4.5",
【问题讨论】:
-
clickHandler有什么用?
-
你能分享更多代码吗?
-
您使用的是哪个版本的样式组件?
-
在 componentDidMount() 中将点击处理程序添加到文档中。据我所知,我的代码与建议的答案中列出的相同。