![](/img/trans.png)
[英]Cannot read property 'value' of undefined for this.refs.variable.value
[英]Cannot read property 'refs' of undefined
我想在React中獲得ref的值時遇到問題。
class Views_Find_Find extends React.Component {
constructor(props){
super(props);
this.state = {value: ''};
this.handleChange = this.handleChange.bind(this);
this.handleClick = this.handleClick.bind(this);
this.handleRedirect = this.handleRedirect.bind(this);
}
handleClick(e){
e.preventDefault();
axios.get('/recherche/'+this.state.value)
.then(function(response){
// Affichage dans les champs
// ReactDOM.findDOMNode(this.refs.span_client).render("test");
console.log(this.refs.span_client.getInputDOMNode().value);
})
.catch(function (error) {
console.log(error);
});
}
handleChange(event){
this.setState({value: event.target.value});
}
handleRedirect(event){
window.location.replace("/amont/"+this.state.value);
}
render() {
var data = this.props.data;
return (
<div className="div_recherche">
<form action="">
<label>Numéro de bon de travail : </label>
<input type="text" name="id_traitement" onChange={this.handleChange}/>
<input type="button" onClick={this.handleClick} value="Recherche un traitement" />
</form>
<table>
<tbody>
<tr>
<td>Client</td>
<td><span id="span_client" className="span_client" ref="span_client">test</span></td>
</tr>
<tr>
<td>Type de traitement</td>
<td><span className="span_type_traitement"></span></td>
</tr>
<tr>
<td>Date de traitement</td>
<td><span className="span_date_traitement"></span></td>
</tr>
<tr>
<td><input type="button" value="Modifier ce traitement" onClick={this.handleRedirect} /></td>
</tr>
</tbody>
</table>
</div>
);
}
}
我看到問題可能出在句柄函數的綁定上,但實際上是在構造函數中綁定了它們。
然后,我嘗試使用getInputDOMNode.value
來console.log
跨度的引用,但是它不起作用。
使用箭頭功能Axios公司成功回調保護范圍內,否則this
並不指向您的組件實例:
axios.get('/recherche/'+this.state.value)
.then((response) => {
//Affichage dans les champs
//ReactDOM.findDOMNode(this.refs.span_client).render("test");
console.log(this.refs.span_client.getInputDOMNode().value);
})
你需要綁定你的愛可信的背景下.then
回調到陣營組件上下文,以便this
關鍵字指向正確的上下文,其中refs
的定義,你可以用綁定或箭頭功能,如做
axios.get('/recherche/'+this.state.value)
.then(function(response){
// Affichage dans les champs
// ReactDOM.findDOMNode(this.refs.span_client).render("test");
console.log(this.refs.span_client.getInputDOMNode().value);
}.bind(this))
.catch(function (error) {
console.log(error);
}.bind(this));
要么
axios.get('/recherche/'+this.state.value)
.then((response) => {
// Affichage dans les champs
// ReactDOM.findDOMNode(this.refs.span_client).render("test");
console.log(this.refs.span_client.getInputDOMNode().value);
})
.catch((error) => {
console.log(error);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.