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

时间:2020-05-23 15:32:12

标签: reactjs react-native expo react-navigation

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

_id

AlbumTitle.js:

<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>

我正在从一个函数调用屏幕,并传递如下的道具:

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;

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

console.log(this.props)

2 个答案:

答案 0 :(得分:1)

您可以这样传递道具:

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

答案 1 :(得分: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.childrenheaderTitle来获取该标题选项

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