React 0.14 - 通过 findDOMNode 使用 refs

React 0.14 - using refs via findDOMNode

我正在尝试使用 refs 在单击按钮时访问输入字段。我编写的语法在 ComponentDidMount 中运行良好,但在单击按钮时出现以下错误。 未捕获的类型错误:无法读取 属性 'refs' of null.

"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;

这是因为当用户点击时,您失去了 this 的上下文。试试这个:

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

您可以在 discussion on React Github 中阅读有关此问题的更多信息。基本上 ES6 方法不会 auto-bind 到 this。您可以像 Thomas 提到的那样使用 bind,也可以使用简洁的箭头函数 -

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