2017-10-05 85 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; }} />