使用类中存在的标头内的'navigation'和'route'-React-navigation v5

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

我被困在想切换到V5版本的反应导航的位置。在v4中,我过去常常传递参数,并与:

一起使用
  • 设置:

this.props.navigation.navigate('MyDestination', {myParam: 'value'})

  • 获取:

this.props.navigation.getParam('myParam')

使用v5,有些事情发生了变化,现在我无法使用this.props.navigation,因为该应用似乎无法识别它。

我的代码被拆分,所以我的App.js只引用了Navigation类:

import React from 'react';
import { StyleSheet, Text, View } from 'react-native'
import Navigation from './navigation/Navigation'

export default function App() {
  return (
      <Navigation/>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});

然后我的导航文件包含所有导航机制(我尚未添加我的TabBar,因为我想先修复基本导航):

import { NavigationContainer } from '@react-navigation/native'
import { createStackNavigator } from '@react-navigation/stack'
import { createBottomTabNavigator } from 'react-navigation-tabs'
import { StyleSheet, Image } from 'react-native'
import React from 'react'
import Home from '../components/Home'
import LendList from '../components/LendList'
import AddMoney from '../components/AddMoney'
import AddStuff from '../components/AddStuff'
import Settings from '../components/Settings'
import Test from '../components/Test'

function HomeScreen() {
    return(
        <Home/>
    )
}

function LendListScreen() {
    return(
        <LendList/>
    )
}

const Stack = createStackNavigator()

function App() {
    return(
        <NavigationContainer>
            <Stack.Navigator initialRouteName="Home">
                <Stack.Screen name="Home"
                component={Home} 
                options={{ title: "Home Page"}}
                />
                <Stack.Screen name="LendList" 
                component={LendList}
                options={{ title: 'Liste' }}
                />
                <Stack.Screen name="AddMoney"
                component={AddMoney} 
                options={{ title: "Ajout Money"}}
                />
                <Stack.Screen name="AddStuff"
                component={AddStuff} 
                options={{ title: "Ajout Stuff"}}
                />
                <Stack.Screen name="Settings"
                component={Settings} 
                options={{ title: "Settings"}}
                />
                <Stack.Screen name="Test"
                component={Test} 
                options={{ title: "Test"}}
                />
            </Stack.Navigator>
        </NavigationContainer>
    )
}

export default App

然后进入我的每个页面(用类编码),这是一个示例,Home.js(我删除了所有Style部分以缩短此处显示的代码):

import React from 'react'
import { StyleSheet, Text, Image, View, Button, TouchableOpacity } from 'react-native'
import Moment from 'react-moment'
import { CommonActions } from '@react-navigation/native'
import { useNavigation } from '@react-navigation/native'

class Home extends React.Component {

    static navigationOptions = () => {

        return {
            headerRight: () => <TouchableOpacity style={styles.settings_touchable_headerrightbutton}
                            onPress={() => this.goToSettings()}>
                            <Image style={styles.settings_image}
                            source={require('../assets/ic_settings.png')} />
            </TouchableOpacity>
        }
    }

    constructor(props) {
        super(props)
        this._goToSettings = this._goToSettings.bind(this)
    }

    _updateNavigationParams() {
        navigation.setParams({
          goToSettings: this._goToSettings
        })
    }

    componentDidMount(){
        console.log("navigation")
        this._updateNavigationParams()

    }

    _checkMoneyDetails(navigation){
        navigation.navigate('LendList', {type: 'Money'})
    }

    _checkStuffDetails(navigation){
        navigation.navigate('LendList', {type: 'Stuff'})
    }

    _checkPeopleDetails(navigation){
        navigation.navigate('LendList', {type: 'People'})
    }

    _goToSettings = () => {
        navigation.navigate('Settings')
    }

    render(){
        const date = new Date();
        const { navigation } = this.props;

        return(
            <View style={styles.main_container}>
                <View style={styles.header_view}>
                    <Text style={styles.header_text}>GiViToMe</Text>
                    <Text style={styles.header_text}>Nous sommes le :{' '}
                    {/* TODO: Penser à gérer ensuite les formats de date étrangers */}
                        <Moment element={Text} format="DD/MM/YYYY" date={date}/>
                    </Text>
                </View>
                <View style={styles.lend_view}>
                    <Text style={styles.title_lend_text}>Vos prêts :</Text>
                    <View style={styles.money_stuff_view}>
                        <View style={styles.money_view}>
                            <View style={styles.money_data_view}>
                                <Image source={require('../assets/ic_money.png')} style={styles.home_img} />
                                <Text>XXX $</Text>
                            </View>
                            <Button title='Money' onPress={() => {this._checkMoneyDetails(navigation)}}/>
                        </View>
                        <View style={styles.stuff_view}>
                            <View style={styles.stuff_data_view}>
                                <Image source={require('../assets/ic_box.png')} style={styles.home_img} />
                                <Text>XXX objets</Text>
                            </View>
                            <Button title='Stuff' onPress={() => {this._checkStuffDetails(navigation)}}/>
                        </View>
                    </View>
                    <View style={styles.people_view}>
                        <View style={styles.people_data_view}>
                            <Image source={require('../assets/ic_people.png')} style={styles.home_img} />
                            <Text>XXX people</Text>
                        </View>
                        <Button title='People' onPress={() => {this._checkPeopleDetails(navigation)}}/>
                    </View>
                </View>
                <View style={styles.footer_view}>
                    <Text style={styles.text_footer_view}>a.vescera inc.</Text>
                </View>
            </View>
        )
    }    
}

export default Home

我的问题是,根据在线文档,我看到要在一个类中使用“导航”或“路线”,我应该在const navigation = { this.props }函数之后使用render()

这个问题是,要在标头中使用一个特定的功能,我必须在componentDidMount()函数之后绑定它,但是render()下的值尚不知道。

我该如何解决? (确保在给定的示例中,导航部分中的所有代码都允许轻松使用navigationroute,但您了解我必须拆分代码。

谢谢。

class routes header navigation react-navigation
1个回答
0
投票

好,所以每次都一样,我尝试了很多天来解决我的问题,当我最终决定发布到堆栈上时,我找到了一个解决方案:)。

因此,如果出现性能问题或其他问题,请查看我的代码,不要犹豫,纠正我。我只是发现此解决方案解决了我的问题。

因此,在我的Navigation.js文件中,我只是通过导航和路由对象使它们可用,这要归功于类中的道具,例如:

function App() {
    return(
        <NavigationContainer>
            <Stack.Navigator initialRouteName="Home">
                <Stack.Screen name="Home"
                component={Home} 
                options={({route, navigation}) => (
                    {headerTitle: 'Home Page', 
                    route: {route}, 
                    navigation: {navigation}}
                )}
                />
            </Stack.Navigator>
        </NavigatorContainer>
)}

然后在我的课程中,我只调用this.props.navigationthis.props.route并从我需要的这些对象中收集。

另一件事是,对于那些将使用此代码来构建类似内容的人,我还必须更改显示标题按钮的方式。我不再使用static navigationOptions = () => {}。我只是直接在navigation.setOptions函数内添加ComponentDidMount代码,如下所示:

navigation.setOptions({
            headerRight: () => <TouchableOpacity style={styles.settings_touchable_headerrightbutton}
                            onPress={() => route.params.goToSettings()}>
                            <Image style={styles.settings_image}
                            source={require('../assets/ic_settings.png')} />
            </TouchableOpacity>
        })

由于我使用的是在类中声明的函数,所以我必须这样做,所以我必须像this._goToSettings = this._goToSettings.bind(this)这样将其绑定在构造函数中,然后将其添加到navigation.setParams函数中。

© www.soinside.com 2019 - 2024. All rights reserved.