[使用React Navigation的headerTitle时道具传递不正确

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

我正在像这样使用堆栈屏幕:

<NavigationContainer>
<Stack.Navigator>
  /* There's also the stack screen for calling the Albums screen here as well. */
  <Stack.Screen
    name="Albums"
    component={Albums}
    options={{
      headerStyle: {
        backgroundColor: "#191414",
      },
      headerTitle: (props) => <AlbumTitle {...props} />,
    }}
  />
</Stack.Navigator>
</NavigationContainer>

AlbumTitle.js:

import React, { Component } from "react";
import { View, Text } from "react-native";

class AlbumTitle extends Component {
  render() {
    console.log(this.props);
    return (
      <View>
        <Text>{this.props.name}</Text>
      </View>
    );
  }
}

export default AlbumTitle;

而且我正在从一个函数调用屏幕并像这样传递道具:

this.props.navigation.navigate("Albums", {
  id,
  name,
});

这不是应该怎么做?一旦函数调用了屏幕并传递了ID和名称,则在呈现时,它还应该将道具传递给AlbumTitle以便显示名称,但它不能像这样工作,相反,console.log(this.props)返回:

Object {
  "allowFontScaling": undefined,
  "children": "Albums",
  "onLayout": [Function anonymous],
  "style": undefined,
  "tintColor": undefined,
}
reactjs react-native expo react-navigation
2个回答
1
投票

您可以传递道具:

<Stack.Screen
  name="Albums"
  component={Albums}
  options={({ route }) => ({
    title: route.params.name,
    headerStyle: {
      backgroundColor: "#191414",
    },
    headerTitleStyle: {
      color: "white",
    },
  })}
/>

0
投票

请参考文档的此部分以在AlbumTitle组件https://reactnavigation.org/docs/headers/#using-params-in-the-title中显示动态标题>

  <Stack.Screen
        name="Albums"
        component={Albums}
        options={({ route }) => ({ title: route.params.name })}
      />

基本上,您需要在title组件中设置一个选项变量props.children并使用headerTitle来获取该标题选项

class AlbumTitle extends Component {
  render() {
    return (
      <View>
        <Text>{this.props.children}</Text>
      </View>
    );
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.