我反应我有一个组件,它有这个代码来检测组件外是否有点击:
export class Cart extends React.Component {
handleClick(e) {
if (!ReactDOM.findDOMNode(this).contains(e.target)) {
console.log('testing=e.target', e.target)
}
}
componentWillMount() {
document.addEventListener('click', this.handleClick, false);
}
componentWillUnmount() {
document.removeEventListener('click', this.handleClick, false);
}
render()
{
return (<div>hello</div>)
}}
但是我在findDOMNode语句中遇到错误:
Uncaught Error: Element appears to be neither ReactComponent nor DOMNode
我该如何解决这个问题?
答案 0 :(得分:0)
您可以将id属性添加到div组件,然后按如下方式重构代码:
export class Cart extends React.Component {
handleClick(e) {
if (e.target.id === 'div') {
console.log('inside')
} else {
console.log('outside!')
}
}
componentWillMount() {
document.addEventListener('click', this.handleClick, false);
}
componentWillUnmount() {
document.removeEventListener('click', this.handleClick, false);
}
render()
{
return (
<div id="div">
hello
</div>)
}
}