this.refs 在 React 中是一个空对象
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"]
}
我在 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"]
}