我想通过引用来访问一个输入字段的按钮的点击。我写的语法在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;
是的,我知道了。谢谢。 “this.refs.Url”也可以在绑定后直接使用。 –
但我猜测绑定是没有必要的,如果我们在里面React.createClass()工作。是吗? –
nope,createClass autobinds,不知道它是否会在React中永远存在。 –