1
我在handleSubmit函数中访问this.refs时遇到问题。this.refs是React中的空对象
我的容器是这样的:
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。
为什么在handle中访问this.refsSubmit不起作用?
这个小提琴做工精细:https://jsfiddle.net/free_soul/49bdw76z/ –
@mrguest是否删除了一些代码?如果是的话,请检查我的答案在这里http://stackoverflow.com/a/40708397/1785635 – abhirathore2006
@ abhirathore2006我没有剥离任何代码...可能是在组件的父母的问题? (这个通过{this.props.children}通过react-router呈现) –