我必须在renderItem函数内部调用一个函数,该函数针对FlatList数据中的每个项目调用。该函数将来自它所来自的组件,并使用组件的少量状态,但是,在获取该方法或就此而言,组件状态中的数据时,它始终会返回一个错误,即该方法未定义。
这是方法以及FlatList的外观
renderItem({ item, index }) {
return (
<TouchableOpacity onPress={() => {this.goToStaffMemberPage(item.id)} }>
<View style={GenericStyles.styles.genericCard}>
<Text style={GenericStyles.styles.genericCardTitle}> {item.first_name.toUpperCase() + " " + item.last_name.toUpperCase()} </Text>
<Text style={GenericStyles.styles.genericCardDescription}> {item.role_name.toUpperCase()} </Text>
</View>
</TouchableOpacity>
);
}
<FlatList
data={this.state.staffList}
keyExtractor={(item, index) => index.toString()}
renderItem={this.renderItem}
contentContainerStyle={GenericStyles.styles.genericContainer}
/>
这是因为您没有授予它访问this
的权限。您可以绑定它(在constructor
中为首选),方法是:
constructor(props){
super(props);
this.renderItem.bind(this);
}
或在定义renderItem时直接使用箭头功能:
renderItem = ({ item, index }) => {
return (
<TouchableOpacity onPress={() => {this.goToStaffMemberPage(item.id)} }>
<View style={GenericStyles.styles.genericCard}>
<Text style={GenericStyles.styles.genericCardTitle}> {item.first_name.toUpperCase() + " " + item.last_name.toUpperCase()} </Text>
<Text style={GenericStyles.styles.genericCardDescription}> {item.role_name.toUpperCase()} </Text>
</View>
</TouchableOpacity>
);
}