reactjs – _this2.pressRow不是一个函数
发布时间:2020-12-15 16:18:24 所属栏目:百科 来源:网络整理
导读:我正在尝试学习React Native,目前正在尝试创建列表视图.一切都正常加载,这个问题出现在连续的压力,我得到以下错误. 我来自web和objective-c背景,所以这需要花一点时间才能进入.这是我用于屏幕的代码. import React,{ Component } from 'react'import { Style
我正在尝试学习React Native,目前正在尝试创建列表视图.一切都正常加载,这个问题出现在连续的压力,我得到以下错误.
我来自web和objective-c背景,所以这需要花一点时间才能进入.这是我用于屏幕的代码. import React,{ Component } from 'react' import { StyleSheet,Text,View,ListView,TouchableHighlight } from 'react-native' export default class FeedView extends Component { static navigationOptions = { title: 'Chat with Feed',}; constructor() { super(); const ds = new ListView.DataSource({rowHasChanged: (r1,r2) => r1 !== r2}); this.state = { dataSource: ds.cloneWithRows(['row 1','row 2']),}; } render() { const { navigate } = this.props.navigation; return ( <View> <ListView dataSource={this.state.dataSource} renderRow={this._renderRow} /> </View> ); } _renderRow( rowData: string,sectionID: number,rowID: number,highlightRow: (sectionID: number,rowID: number) => void ){ return ( <TouchableHighlight onPress={() => { this._pressRow(rowID); highlightRow(sectionID,rowID); }}> <View> <View style={styles.row}> <Text style={styles.text}>Testing</Text> </View> </View> </TouchableHighlight> ); } _pressRow( rowID: number ){ } } var styles = StyleSheet.create({ row: { flexDirection: 'row',justifyContent: 'center',padding: 10,backgroundColor: '#F6F6F6',} }); 解决方法
如上面的注释和上面所述,如果您希望在其他方法中访问此变量,则需要将ES6类方法与此绑定,因为它们不会自动绑定.
我建议将所有绑定放在构造函数中,因为它被认为是一种很好的做法(减少垃圾收集)并使您的代码更整洁.有关更多信息,请参阅相关的ESLint page. constructor(props) { super(props); ... this._renderRow = this._renderRow.bind(this); this._pressRow = this._pressRow.bind(this); } 然后,您可以在类中单独使用this._renderRow,而无需担心绑定. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |