【问题标题】:Passing React Navigation to Child of Child Component将 React Navigation 传递给子组件的子组件
【发布时间】:2018-05-12 20:25:12
【问题描述】:

我正在使用子“行”和“按钮”组件动态构建我的“屏幕”。我只使用这种方法是因为我找不到可用于 react-native 的 flex-flow 属性。

所以基本上我通过数组数组进行映射以构建每一行,并在行内映射通过每个数组以构建每个按钮。因为 onPress 需要在按钮中设置,所以我为每个传递 URL onPress{() => this.props.navigation.navigate({navigationURL})

作为道具,先到行,再到按钮。问题是我不断收到错误'Cannot read property 'navigation' of undefined。我确定这是因为只有导航器中的实际“屏幕”才能访问导航道具。我也试过通过

navigation={this.props.navigation}

但没有成功。我浏览了所有文档,似乎找不到任何有用的东西。有没有人遇到过类似的情况?

【问题讨论】:

    标签: reactjs react-native react-navigation react-props


    【解决方案1】:

    如果您想从不属于navigator 的组件访问navigation 对象,则将该组件包装在withNavigation HOC 中。在包装的组件中,您可以使用this.props.navigation 访问导航。看看official document

    示例

    import { withNavigation } from 'react-navigation';
    ...
    class CustomButton extends React.Component {
      render() {
        return <Button title="Back" onPress={() => { 
          this.props.navigation.goBack() }} />;
        }
    }
    
    export default withNavigation(CustomButton);
    

    希望这会有所帮助!

    【讨论】:

    • 感谢您的回复。我只是尝试过,但仍然有困难。我是否需要用 wrapNavigation 包装子行组件和按钮组件的子组件?
    • 根据文档,您只需要包装您将使用navigation 的组件。顺便说一句,您现在遇到什么错误?
    • 如果您使用this.props.navigation 访问navigation 并收到错误Cannot read property 'navigation' of undefined,这意味着this.props 未定义,这不应该是因为props 始终可用于组件.顺便说一句,this 引用了组件,你有没有使用arrow function 或bind 和this 的功能?你能分享你访问的代码吗this.props.navigation
    【解决方案2】:

    啊,愚蠢的错误。我没有在构造函数中设置道具。谢谢Prasun Pal 的帮助!如果其他人有问题,这是我的代码。

     import React, { Component } from 'react'
        import { Image, Text, TouchableOpacity, View } from 'react-native'
        import { withNavigation } from 'react-navigation'
    
    
    
        class ButtonName extends Component {
    
            constructor(props) {
                super(props);
                this.state = {};
              }
    
            render() {
                return (
    
                    <TouchableOpacity
                        onPress={() => this.props.navigation.navigate('PageName')}
                    >
                    </TouchableOpacity>
                )
            }
        }
    
        export default withNavigation(ButtonName);
    

    【讨论】:

      猜你喜欢
      • 2019-12-17
      • 1970-01-01
      • 2019-01-20
      • 2022-01-18
      • 1970-01-01
      • 2022-07-15
      • 1970-01-01
      • 2020-05-08
      • 1970-01-01
      相关资源
      最近更新 更多