2017-10-05 12 views
0

コンポーネントから値を取得しようとしていますが、定義されていないrefを取得し続けています。 ここに私のコードです。関数onClickSave()からthis.refsを取得してTextInputCellコンポーネントのref "input"の値を取得しようとしましたが、未定義です。私のコードは間違っていますか?ネイティブに反応します。 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に渡すと、この関数が実際に呼び出されるときには未定義の になります。

2番目の文字列の参照はもう推奨されません。あなたは機能的なものを使うべきです。その詳細情報here

レガシーAPI:あなたは以前にリアクトで働いていた場合は文字列の参考文献

は、あなたは、ref属性が文字列「にtextInput」のように、ある古い API、および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; }} /> 
関連する問題