FlatList rendeItem 组件无法识别“this”关键字
FlatList rendeItem component doesn't recognize `this` keyword
我必须在 renderItem 函数中调用一个函数,该函数为 FlatList 数据中的每个项目调用。该函数将来自它所来自的组件并使用该组件的一些状态,但是,它总是 returns 一个错误,即在获取该方法或就此而言获取数据时该方法未定义在组件的状态下。
这是方法以及 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>
);
}
我必须在 renderItem 函数中调用一个函数,该函数为 FlatList 数据中的每个项目调用。该函数将来自它所来自的组件并使用该组件的一些状态,但是,它总是 returns 一个错误,即在获取该方法或就此而言获取数据时该方法未定义在组件的状态下。
这是方法以及 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>
);
}