[英]this.refs is an empty object in React
我在handleSubmit函數中訪問this.refs時遇到問題。
我的容器看起來像這樣:
import React, { Component } from 'react'
import { Link } from 'react-router'
import { connect } from 'react-redux'
import { getSomeStuff } from '../actions/someApiActions’
class MyClass extends Component {
componentWillMount() {
this.props.dispatch(getSomeStuffFromApi(this.props.params.cuid))
}
handleSubmit = () => {
console.log(this.refs) // always console logs an empty object {}
}
render() {
if(!this.props.results.item){
return (
<div>... loading …</div>
)
}
const { name } = this.props.results.item.stuff
return (
<div>
<p><input ref="name" defaultValue={ name }/></p>
<button type="submit" onClick={this.handleSubmit}>Update</button>
</div>
)
}
}
const mapStateToProps = (state) => {
return {
results: state.getSomeStuff
}
}
export default connect(mapStateToProps)(MyClass)
當我單擊提交按鈕時,handleSubmit將始終記錄一個空對象(即使輸入在html中正確呈現)。 我注意到我可以在componentDidUpdate方法中訪問this.refs而沒有任何問題。
為什么在handleSubmit中訪問this.refs不起作用?
大聲笑! 問題在於babel翻譯。 在.babelrc我一直在使用這個預設:
{
"presets": ["react", "node7", "stage-1"]
}
我不得不改變它:
{
"presets": ["react", "es2015", "stage-1"]
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.