我在 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 不起作用?