我在index.js
中有一个 ListView 我的 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
中的此模板绑定(bind)列表项文件如下。
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;
如果我从 ListView 中选择一行 onPress
事件调用。和onPressRow
函数被执行。来自onPressRow
我调用了另一个在名为“updateDate
”的类中定义的函数。我这样称呼this.updateDate();
但得到了undefined is not a function error
。
我做错了什么?
提前致谢。
最佳答案
您需要绑定(bind)
该函数,因为this
没有引用代码中的适当上下文。您可以使用箭头功能
onPressRow = () => {
try {
console.log("Selected!");
//Some operation
this.updateDate();
} catch (error) {
console.error(error);
}
}
绑定(bind)函数的另一种方法是在构造函数中设置绑定(bind)
constructor() {
super();
this.onPressRow = this.onPressRow.bind(this);
}
事实上,您需要绑定(bind)
任何使用this
的函数来引用您的React类的上下文
。
关于javascript - 如何从导入的元素访问父函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41734466/