【问题标题】:React navigation 5 : Pass arguments with NavigationReact Navigation 5:使用 Navigation 传递参数
【发布时间】:2021-01-07 18:01:42
【问题描述】:

我正在使用带有 react navigation5 的类组件,我有两个类:

类 DrawerComponent.js

export default class DrawerContent extends Component{   
constructor(props){
 super(props);    
}
render(){
 return(
    <View style={{flex:1}}>
        <DrawerContentScrollView {...this.props}>            
                <Drawer.Section style={styles.drawerSection}>
                    {
                          <DrawerItem 
                                icon={({color,size}) => (
                                 <Icon 
                                 name=""
                                 color={color}
                                 size={size}
                                 />
                                )}
                                label={menu.localizedTitle}
                                onPress = {() =>**{this.props.navigation.navigate("RecordList",{body :'abc' }**)}}/>)
        </Drawer.Section>             
            </View>
        </DrawerContentScrollView>         
    </View>
)}}

现在如果我必须在另一个类中访问 body 的值,我该怎么做?

【问题讨论】:

  • 我得到一个错误 getParam is not a func
  • 对不起,我的错。你说 react-navigation 5,它适用于 v4。 Ketan 的回答是有效的。

标签: react-native react-navigation react-navigation-v5


【解决方案1】:

在您的RecordList 组件中,您可以使用route 访问参数

const RecordList = ({navigation, route})=>{
  const {body} = route.params;
  console.log(body)
}

在基于类的组件中:

class RecordList extends Component{
  
  render(){
    const {body} = this.props.route.params;
    console.log(body)
    return <View><Text>{body}</Text></View>
  }
}

【讨论】:

  • 你能用类组件写这个吗?我不知道如何用类组件格式写这个。类似于我在上面写的内容
  • 在基于类的组件中,您可能必须使用const {body} = this.props.route.params
  • 不,它说无法读取未定义的属性'body'
  • 已更新。 const {body} = this.props.route.params
【解决方案2】:

我在drawerNavigator中使用stackNavigator,所以我将不得不使用嵌套导航:

 this.props.navigation.navigate('RecordList', {screen:'Home',params :{ title: "Home"}})

并且可以完全按照上面 Ketan 的回答中的方式进行检索。

【讨论】:

    猜你喜欢
    • 2020-05-29
    • 1970-01-01
    • 1970-01-01
    • 2020-05-23
    • 1970-01-01
    • 1970-01-01
    • 2020-09-07
    • 2017-12-19
    • 1970-01-01
    相关资源
    最近更新 更多