react:addEventListener不是函数错误

时间:2016-09-03 19:48:41

标签: reactjs

我在组件

中的render方法中有这个div
<div ref={node => this.domNode = node} style={this.getStyle()}>{ this.props.children }</div>

当我在componentDidMount中执行此操作时

this.domNode.addEventListener('mousedown', this.onDrag); 

出现错误

this.domNode.addEventListener is not a function

3 个答案:

答案 0 :(得分:1)

你的引用回调的arguemnt(node)可以是null。您需要在绑定侦听器之前检查它。

  

请注意,当卸载引用的组件时,每当ref更改时,将使用null作为参数调用旧的ref。

来自https://facebook.github.io/react/docs/more-about-refs.html#the-ref-callback-attribute

答案 1 :(得分:0)

你必须在它周围放置一个ReactDOM.findDOMNode。

componentDidMount = () => {
   ReactDOM.findDOMNode(this.domNode).addEventListener('mousedown', this.onDrag);
}

答案 2 :(得分:0)

我正在使用React的16.6.3版本,也遇到了您的问题,使用此方法可以解决该问题。

componentDidMount() {
    let domNode = ReactDOM.findDOMNode(this.domNode);
    if(domNode) {
      domNode.addEventListener('mousedown', this.props. onDrag);
    }
}