将反应导航中的导航参数传递给组件的方法

问题描述 投票:0回答:1

[试图弄清楚如何在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>
        );
    }
}
android ios react-native navigation react-navigation
1个回答
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>
        );
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.