我一直在使用 wix/react-native-navigation 包在屏幕之间导航并正确处理堆栈。
跨屏幕移动非常简单,按下按钮时会触发这些转换。但是,当我有一个 FlatList 并且我想在用户点击列表中的项目时推送到新屏幕时,问题就出现了,看起来开始时注入(inject)的导航器 Prop 丢失了,或者处于 onPress 回调事件之外的另一个上下文中;
这是示例代码
class AlertType extends React.PureComponent {
_onPress = () => {
this.props.onPressItem(this.props.itemId, this.props.itemName, this.props.itemImageUrl);
};
render() {
return (
<TouchableOpacity { ...this.props }
onPress={ this._onPress }
style={ itemStyle.cardContainer }>
<View style={ itemStyle.mainContainer }>
<View style={{ width: 10 }}/>
<Image
source={{ uri: NET.HOST + this.props.itemImageUrl }}
style={{ width: 45, height: 45 }}
/>
<View style={{ width: 10 }}/>
<Text style={ itemStyle.itemText }>{ this.props.itemName }</Text>
</View>
</TouchableOpacity>
);
}
}
class AlertsScreen extends React.Component {
constructor(props) {
super(props);
this.state = {
alertTypes: null,
}
}
_onAlertTypePressed(typeId: string, typeName: string, imageUrl: string){
this.props.navigator.push({
screen: 'prod.screens.AlertsCreator',
title: 'Alert',
passProps: {
alertId: typeId,
alertName: typeName,
alertImage: imageUrl
}
});
}
_renderListItem = ({ item }) => (
<AlertType
itemName={ item.titulo }
itemId={ item.key }
itemImageUrl={ item.url }
onPressItem={ this._onAlertTypePressed }
/>
);
render() {
return (
<View style={ styles.mainContainer }>
<FlatList
data={ this.state.alertTypes }
ItemSeparatorComponent={ () => <View style={{ height: 5 }}/> }
renderItem={ this._renderListItem }
/>
</View>
);
}
const mapSessionStateToProps = (state, ownProps) => {
return {
session: state.session
};
}
const mapDispatchToProps = (dispatch) => {
return {
actions: bindActionCreators(actions, dispatch)
};
}
export default connect(mapSessionStateToProps, mapDispatchToProps)(AlertsScreen)
一定是我遗漏了一些东西,我知道 this.props.navigator 不是未定义的,但在 _onAlertTypePressed
内部 navigator 属性未定义。
最佳答案
问题在于您将函数传递给组件而没有将其绑定(bind)到当前上下文。
你应该通过:
this._onAlertTypePressed.bind(this);
另一种方法是在构造函数中绑定(bind)函数:
constructor(props) {
this._onAlertTypePressed = this._onAlertTypePressed.bind(this);
}
关于javascript - 从被按下的平面列表项导航到另一个屏幕,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49459247/