2016-01-20 27 views
1

我想通过引用来访问一个输入字段的按钮的点击。我写的语法在ComponentDidMount中正常工作,但单击按钮时会出现以下错误。未捕获的TypeError:无法读取null的属性'refs'。反应0.14 - 通过findDOMNode使用引用

"use strict" 

import React from 'react' 
import ReactDOM from 'react-dom' 

class Dashboard extends React.Component { 
    componentDidMount() { 
     console.log("in component did mount", ReactDOM.findDOMNode(this.refs.Url)) 
    } 
    shortenURL() { 
     console.log("in function", ReactDOM.findDOMNode(this.refs.Url)) //Gives error: Uncaught TypeError: Cannot read property 'refs' of null 
    } 
    render() { 
     return (
      <div className="container"> 
      <form> 
      <div className="create-board"> 
      <div className="board-header"> 
       <h3 className="board-header-h3">URL Shortener</h3> 
      </div> 
      <div className="control-group txt-control"> 
       <div className="form-group"> 
        <label className="control-label" htmlFor="inputURL">Enter your long URL here</label> 
        <input type="text" ref="Url" className="form-control" placeholder="Enter Your Long URL here"></input> 
       </div> 
       <div className="control-group but-control"> 
       <div className="controls"> 
        <button className="btn btn-info" type="button" onClick={this.shortenURL}>Shorten</button> 
       </div> 
       </div> 
      </div> 
      </div> 
     </form> 
      </div> 
     ) 
    } 
} 
export default Dashboard; 

回答

0

这是因为你失去的上下文当用户点击。试试这个:

<button className="btn btn-info" type="button" onClick={this.shortenURL.bind(this)}>Shorten</button> 
+0

是的,我知道了。谢谢。 “this.refs.Url”也可以在绑定后直接使用。 –

+0

但我猜测绑定是没有必要的,如果我们在里面React.createClass()工作。是吗? –

+0

nope,createClass autobinds,不知道它是否会在React中永远存在。 –

0

您可以在discussion on React Github中了解关于此问题的更多信息。基本上ES6方法不会自动绑定到this。您可以使用bind托马斯提到的,或者你可以使用简洁Arrow功能 -

onClick={(e) => this.shortenURL()}