【问题标题】:How to access parent function from imported element [duplicate]如何从导入的元素访问父函数[重复]
【发布时间】:2017-01-19 05:35:17
【问题描述】:

我在index.js 我的 React Native 项目中有一个列表视图,如下所示。

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

我做错了什么?

提前致谢。

【问题讨论】:

  • 绑定函数或使用箭头函数! this.onPressRow = this.onPressRow.bind(this); 在构造函数中。
  • @AndrewLi 谢谢。现在修复:)

标签: javascript reactjs react-native ecmascript-6


【解决方案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

【讨论】:

  • 您的示例不是有效的 ECMAScript 6。如果您解释了如何使这个(实验性)功能发挥作用,这对其他人会很有用。
猜你喜欢
  • 1970-01-01
  • 2014-07-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多