试图弄清楚如何在react-navigation
中传递参数。用户使用左标题按钮从“过滤器”中选择了一个选项后,应使用该过滤器作为参数调用loadItems(filter)
。我该如何捕捉这样的事件?
export default class FavoritesView extends Component {
static navigationOptions = ({navigation}) => ({
headerLeft: (
<Button
onPress={()=>{FavoritesView.showFilteringMenu(navigation)}}
title="Filter"
/>
),
});
static showFilteringMenu(navigation) {
let FILTERS = [
'A',
'B',
'C'
];
ActionSheet.showActionSheetWithOptions({
title: "Filter options",
options: FILTERS
},
(buttonIndex) => {
navigation.setParams({
selectedOption: FILTERS[buttonIndex]
}); // A parameter is set here
});
}
loadItems(filter) { // This function should be called
StorageService.getItems(filter).then(v => this.setState({ data: v }));
}
render() {
let {navigation} = this.props;
return (
<SafeAreaView style={styles.container}>
<NavigationEvents
onWillFocus={payload => this.loadItems()} // This works only for initial load
/>
</SafeAreaView>
);
}
}
答案 0 :(得分:0)
这是我使用navigation.getParam()
和navigation.setParams()
来解决的方法。
export default class FavoritesView extends Component {
static navigationOptions = ({navigation}) => ({
headerLeft: (
<Button
onPress={navigation.getParam('showFilteringMenu')}
title="Filter"
/>
),
});
static showFilteringMenu() {
let FILTERS = [
'A',
'B',
'C'
];
ActionSheet.showActionSheetWithOptions({
title: "Filter options",
options: FILTERS
},
(buttonIndex) => {
this.selectedFilter = FILTERS[buttonIndex];
this.loadItems(this.selectedFilter);
});
}
componentDidMount() {
this.props.navigation.setParams({
showFilteringMenu: this._showFilteringMenu.bind(this)
});
}
loadItems(filter) { // This function should be called
StorageService.getItems(filter).then(v => this.setState({ data: v }));
}
render() {
let {navigation} = this.props;
return (
<SafeAreaView style={styles.container}>
<NavigationEvents
onWillFocus={payload => this.loadItems()} // This works only for initial load
/>
</SafeAreaView>
);
}
}