如何将 Prop 传递给导航屏幕组件 - React Native

2024-01-21

我对 React Native 还很陌生。我在 App.js 文件中创建了一个抽屉导航器。

我的导航组件之一是一个名为登录界面.

我正在尝试将道具传递给登录界面当用户导航到它时显示。

App.js(导航器)

const Tab = createMaterialBottomTabNavigator()
const Stack = createStackNavigator()
const Drawer = createDrawerNavigator()

export default class App extends Component {
    constructor(props) {
        super(props)

        this.state = {
            isAdmin: 'false',
            checked: false,
        }
    }

    async componentDidMount() {
        try {
            const adm = await AsyncStorage.getItem('is_admin')
            if (adm == null) {
                adm = await AsyncStorage.setItem('is_admin', 'false')
            }
            this.setState({ isAdmin: adm, checked: true })
        } catch (error) {
            console.log(error)
        }
    }


    render() {
        const { isAdmin } = this.state
        console.log(isAdmin)

        //is admin
        return isAdmin == 'true' ? (
            <NavigationContainer>
                <Drawer.Navigator initialRouteName="Home">
                    <Drawer.Screen name="Home" component={MyStack} />

                    <Drawer.Screen
                        name="Admin Panel"
                        component={props => {
                            return <LoginScreen props={props} propName = {'Hello'} />
                        }}
                    />
                </Drawer.Navigator>
            </NavigationContainer>
        ) : (
            //ISNOT ADMIN
            <NavigationContainer>
                <Drawer.Navigator initialRouteName="Home">
                    <Drawer.Screen name="Home" component={MyStack} />

                    <Drawer.Screen name="Login" component={LoginScreen} />
                </Drawer.Navigator>
            </NavigationContainer>
        )
    }
}

LginScreen.js

    const LoginScreen = ({ navigation, propName }) => {
       // const [bridge, setB] = useState(false)

        return (
            <SafeAreaView style={{ flex: 1, backgroundColor: '#376772' }}>
                <TopHeader
                    onRefresh={() => fetch_crossings}
                    onMenuToggle={() => navigation.toggleDrawer()}
                />

                <View style={{ flex: 1 }}>
                    <View
                        style={{
                            backgroundColor: '#fff',
                            margin: 10,
                            borderRadius: 5,
                            alignItems: 'center',
                            padding: 10,
                            paddingBottom: scale(20),
                        }}
                    >
                        <Avatar
                            rounded
                            size={'xlarge'}
                            overlayContainerStyle={{
                                backgroundColor: '#185a9d',
                            }}
                            icon={{
                                color: 'orange',
                                type: 'ionicon',
                                name: 'ios-log-in',
                            }}
                        />
                        <Input
                            placeholder="  Email"
                            placeholderTextColor={'#292b2c'}
                            style={{ margin: 5 }}
                            errorStyle={{ color: '#d9534f' }}
                            leftIcon={<Icon name="mail" color="#292b2c" />}
                            errorMessage="Enter a valid Email"
                        />

                        <Divider
                            style={{
                                backgroundColor: 'orange',
                                height: 3,
                                margin: scale(20),
                                borderRadius: 3,
                            }}
                        />
                        <Input
                            placeholder="  Password"
                            placeholderTextColor={'#292b2c'}
                            secureTextEntry={true}
                            style={{ margin: 5 }}
                            errorStyle={{ color: '#d9534f' }}
                            leftIcon={<Icon name={'lock'} color="#292b2c" />}
                            errorMessage="Enter a valid Email"
                        />
                    </View>
                    <View
                        style={{
                            backgroundColor: '#fff',
                            margin: 10,
                            marginTop: 0,
                            borderRadius: 5,

                            padding: 10,
                        }}
                    >
                        <Button
                            buttonStyle={{
                                margin: 10,
                                backgroundColor: '#5cb85c',
                                borderRadius: 4,
                                alignSelf: 'stretch',
                            }}
                            onPress={async () => {
                                try {
                                    await AsyncStorage.setItem('is_admin', 'false')
                        **console.log(propName);** //<--Right HERE

                                    navigation.navigate('Home')

                                } catch (error) {
                                    console.log(error)
                                }
                            }}
                            icon={<Icon name="send" size={15} color="white" />}
                            iconRight
                            titleStyle={{ fontWeight: 'bold' }}
                            title="Submit  "
                        />
                        <Button
                            buttonStyle={{
                                margin: 10,
                                backgroundColor: '#d9534f',
                                borderRadius: 4,
                                alignSelf: 'stretch',
                            }}
                            onPress={() => {
                                navigation.navigate('Home')
                            }}
                            icon={<Icon name="close" size={15} color="white" />}
                            iconRight
                            titleStyle={{ fontWeight: 'bold' }}
                            title={'Close '}
                        />
                    </View>
                </View>
            </SafeAreaView>
        )
    }

    export default LoginScreen

每当我console.log(propName),它说它未定义。


阿萨德的回答实际上帮助我做到了这一点:

App.js(导航)

在这里,我们可以添加'初始参数'参数为<Drawer.Screen/> :

 <Drawer.Screen
    name="Login"
    component={LoginScreen}
    initialParams={{ post: this.state.isAdmin }} //<-- Right here
 />

然后我们可以在 LoginScreen.js 中这样接收 :

const LoginScreen = ({ navigation, route }) => {

    console.log(route.params.post)
    return (
        <Text>{route.params.post}</Text>
    )
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何将 Prop 传递给导航屏幕组件 - React Native 的相关文章

随机推荐

  • 导出 SAS 数据集中的变量类型

    有没有简单的方法来捕获和导出 SAS 数据集中每个变量的类型 我正在将数据集导出为 CSV 格式以读入 R 并且read table如果后者还知道每个变量的数据类型 则后者的过程可以更有效地工作 PROC CONTENTS 有一个 OUT
  • 如何使用 unique_together 建立抽象模型?

    为什么我得到 Error One or more models did not validate test test unique together refers to slug This is not in the same model
  • 使用kinect检测身体关节角度(检查时间间隔)

    正如您在图片中看到的 链接如下 当左手举起时 它会显示一个角度 我想要的是 一个人应该握住他的手臂 5 秒 如图所示的位置 并且如果该人改变其手臂位置 这意味着角度低于 70 度或高于 80 度 5 秒内应显示一些消息 将手臂放回同一位置
  • Plotly 中的 $ 刻度格式化程序尊重负值

    Per the answer https stackoverflow com a 58142945 1840471 to 使用python中的plotly方法在y轴刻度中添加货币符号 https stackoverflow com q 58
  • 根据日期从 git 签出旧提交

    由于与另一个项目 共享此代码 不兼容 我正在尝试从 git 检索旧提交 git 存储库是 OpenZWave 我发现 SO 上有一个帖子说要发出命令 git checkout 14 days ago 但这会导致 warning Log fo
  • 使用 Node jS 的 Redis 配置集

    Team 我正在尝试使用 NODE js 应用程序在运行时设置 redis 的配置 如下所示 让 setConfig 等待 this cacheConnection config set notify keyspace events Ex
  • 获取简单注入器的容器实例

    我正在 ASP NET MVC 项目中使用简单注入器 我添加了SimpleInjector Integration Web Mvcnuget 包 这增加了SimpleInjectorInitializer上课于App Start文件夹并初始
  • 如何禁用特定控件的默认皮肤?

    是否可以有一个不使用 skin 文件中指定的默认外观的控件 我有一个我要做的控件not想要应用默认皮肤 在大多数 ASP NET 书籍中都可以找到此解决方案 使用 EnableTheming
  • 代码隐藏中的 .NET / C# 字符串引用未加载更新值

    我似乎遇到了一个奇怪的问题 即字符串引用没有加载更新的值 简而言之 我替换了一个包含一堆页面标题 例如 HTML 页面标题 的 DLL 文件 App Code dll 但从其他 DLL 引用时 这些值并未更新 以下是示例页面代码隐藏中的代码
  • WPF TreeView,在PreviewMouseDown事件中获取TreeViewItem

    如何确定在 PreviewMouseDown 事件中单击的 TreeViewItem 以下似乎有效 private void myTreeView PreviewMouseDown object sender MouseButtonEven
  • 使用反射输入计算 CRC64 的最有效方法

    我需要使用计算 CRC 64这个设置 https i stack imgur com Tdj7Z png进入这个精彩的网站 http www sunshine2k de coding javascript crc crc js html h
  • MySQL 锁等待超时

    我有错误Lock wait timeout exceeded try restarting transaction 出现这种情况的原因是什么以及如何解决 供参考 innodb lock wait timeout 100在 MySQL 配置文
  • 是否有 FMX 函数可以在运行时设置 TImage 的透明颜色?

    我在 FMX FireMonkey 的表单上有一个 TImage 我想在运行时将位图加载到 TImage 中 其中位图应该具有由位图中第一个像素的颜色定义的透明背景 该颜色可能因位图而异 我知道如何在设计时通过使用 TImage 的 Mul
  • 将变量从伏特发送到自定义函数

    我创建了一个可以从 volt 访问的自定义函数 该函数似乎工作正常 但我无法设法将变量发送到该函数 它将变量作为文本而不是其值发送 树枝功能 volt gt getCompiler gt addFunction getusergroup f
  • 通过WIFI认证后User.Identity.Name为空

    我正在使用 WIFI 登录我的应用程序 一切似乎都很好 日志记录 重定向到网站等 但是当我尝试使用User Identity Name在我的鳕鱼异常被抛出 User为空 有什么想法我做错了吗 我在 VS 2012 上工作 web confi
  • xsl-fo:并行的两份报告,一份在奇数页,另一份在偶数页

    我想生成一个 PDF 其中一个内容流在奇数页 另一个内容流在偶数页 因此当您双面打印 PDF 时 您有一个模板可以在偶数页上写笔记 这是我所拥有的 但它不起作用
  • 使用 Hibernate 管理多租户应用程序中的连接池

    我正在尝试使用单独的架构方法设置多租户应用程序 我正在使用 JPA 和 Hibernate 4 实现 就像 说的ben75 https stackoverflow com users 1818045 ben75在这个非常有用的thread
  • 在 C 中对 int 进行符号扩展

    所以我在获取 int 字段然后对其进行符号扩展时遇到了一些麻烦 我有一个获取 int 字段的方法 getField int value int hi int lo Value 是我从中获取字段的 int hi 和 lo 是字段的大小 所以我
  • 选择所有具有 png 背景图像的 div

    我怎样才能在 jQuery 中选择所有div是有background image url somepath somename png 以他们的风格 尝试添加自定义选择器 document ready function extend expr
  • 如何将 Prop 传递给导航屏幕组件 - React Native

    我对 React Native 还很陌生 我在 App js 文件中创建了一个抽屉导航器 我的导航组件之一是一个名为登录界面 我正在尝试将道具传递给登录界面当用户导航到它时显示 App js 导航器 const Tab createMate