2017-10-05 90 views
0

我想从组件获取值,但不断得到未定义的参考。 这是我的代码。从onClickSave()函数中,我试图让this.refs在TextInputCell组件中获得ref“输入”的值,但它是未定义的。我的代码不正确?反应原生。从属性获取值属性

import React from 'react'; 
import { View, Text } from 'react-native'; 
import { Form, Section, TextInputCell } from 'react-native-forms'; 
import { bindActionCreators } from 'redux'; 
import { connect } from 'react-redux'; 

import ActionBar3 from '../components/ActionBar3'; 
import * as profileActions from '../actions/profileActions'; 

const GLOBAL = require('../GlobalConstants'); 

class ProfileViewEdit extends React.Component { 
    constructor(props) { 
    super(props); 
    this.onClickSave.bind(this); 
    } 

    componentDidMount() { 
    console.log('componentDidMount'); 
    } 

    onClickSave() { 
    console.log('aaabd'); 
    console.log(this.refs); 
    } 

    render() { 
    const title = this.props.navigation.state.params.title; 
    let value = this.props.navigation.state.params.value; 
    return (
     <View style={{ flex: 1, backgroundColor: '#EFEFF4' }}> 
      <ActionBar3 
      barTitle={title} navigation={this.props.navigation} onClickSave={this.onClickSave} 
      /> 
      <Section 
       title={title} 
       //helpText={'The helpText prop allows you to place text at the section bottom.'} 
      > 
       <TextInputCell 
       value={value} 
       ref="input" 
       /> 
      </Section> 
     </View> 
    ); 
    } 
} 

const mapStateToProps = (state) => ({ 
    stateProfile: state.profile 
}); 

const mapDispatchToProps = (dispatch) => ({ 
    actions: bindActionCreators(profileActions, dispatch) 
}); 

export default connect(
    mapStateToProps, 
    mapDispatchToProps 
)(ProfileViewEdit); 

回答

1

首先,您没有正确处理事件。要在您的活动中使用this,您需要绑定this。箭头函数自身绑定它,但您可以手动绑定到。更多信息是here

您必须注意在JSX回调中this的含义。在 JavaScript中,类方法默认没有绑定。如果您忘记 绑定this.handleClick并将其传递给onClick,则在实际调用该函数时,这将是未定义的 。

第二个字符串refs不被建议了。你应该使用功能性的。有关更多信息here

遗留API:字符串参考文献

如果你反应过来的工作,你可能熟悉的旧 API,其中ref属性是一个字符串,如“为textInput”,和DOM 节点访问为this.refs.textInput。我们建议不要这样做,因为 字符串参考文献有一些问题,被视为遗留问题,并且可能会在将来的某个版本中删除 。如果您目前使用 this.refs.textInput来访问参考,我们建议您使用回调模式 。

<ActionBar3 barTitle={title} navigation={this.props.navigation} onClickSave={() => this.onClickSave()} /> 

<TextInputCell value={value} ref={(ref) => { this.inputRef = ref; }} />