2016-11-21 475 views
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不起作用?

+0

这个小提琴做工精细:https://jsfiddle.net/free_soul/49bdw76z/ –

+0

@mrguest是否删除了一些代码?如果是的话,请检查我的答案在这里http://stackoverflow.com/a/40708397/1785635 – abhirathore2006

+0

@ abhirathore2006我没有剥离任何代码...可能是在组件的父母的问题? (这个通过{this.props.children}通过react-router呈现) –

回答

0

哈哈!问题在于巴贝尔翻译。在.babelrc我一直在使用这种预设:

{ 
    "presets": ["react", "node7", "stage-1"] 
} 

我不得不把它改成这样:

{ 
    "presets": ["react", "es2015", "stage-1"] 
}