2017-01-19 40 views
1

我有一个列表视图index.js我的反应如下所示的本地项目。如何从导入元素访问父功能

import ResultRow from './resultRow' 

class ResultList extends Component { 
    constructor() { 

    } 

    updateDate(){ 
     //Some operation 
    } 

    onPressRow() { 
     try { 
      console.log("Selected!"); 

     //Some operation 

      this.updateDate(); // Got undefined is not a function 

     } catch (error) {  
      console.error(error); 
     } 
    } 

    renderRow(rowData) { 
     return (
      <ResultRow 
      onPress={this.onPressRow} 
      {...rowData} /> 
     ) 
     } 

    render() { 
     return (
       <ListView 
       style={[styles.container, { padding: 10, backgroundColor: '#ddd' }]} 
       dataSource={this.state.dataSource} 
       renderRow={this.renderRow.bind(this)} /> 
      ); 
    } 

} 

和绑定列表项resultRow.js文件中像下面使用此模板。

import React from 'react'; 
import { TouchableHighlight, StyleSheet, Image,View } from 'react-native'; 

const ResultRow = (props) => (
    <TouchableHighlight onPress={() => props.onPress()}> 
    <View> 
     <Text>My Row</Text>  
    </View> 
    </TouchableHighlight > 
); 

export default ResultRow; 

如果我从列表视图中选择一列名为onPress事件。并执行onPressRow函数。从onPressRow函数我调用另一个函数,它是在同一个类中定义的“updateDate”。我打电话是这样的this.updateDate();但是得到了undefined is not a function error

我做错了什么?

在此先感谢。

+2

绑定函数或使用箭头函数! 'this.onPressRow = this.onPressRow.bind(this);'在构造函数中。 – Li357

+0

@AndrewLi谢谢。现在修复:) – bCliks

回答

1

您需要bind函数this没有引用您的代码中的适当上下文。您可以使用箭头功能

onPressRow =() => { 
     try { 
      console.log("Selected!"); 

     //Some operation 

      this.updateDate(); 

     } catch (error) {  
      console.error(error); 
     } 
    } 

的绑定你的功能的另一种方法是设置在构造函数中结合

constructor() { 
    super(); 
    this.onPressRow = this.onPressRow.bind(this); 
} 

事实上,你将需要bind任何功能,将利用this参考您的反应类的context

+1

您的示例ECMAScript 6无效。如果您解释为了使此(实验性)功能可以正常工作,请说明如何解决此问题。 –