【问题标题】:props are not being passed correctly when using React Navigation's headerTitle使用 React Navigation 的 headerTitle 时没有正确传递道具
【发布时间】:2020-05-23 15:32:12
【问题描述】:

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

<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 和名称,当它渲染时,它也应该将 props 传递给 AlbumTitle 以便显示名称,但它不是这样工作的,而是 console.log(this.props) 正在返回:

Object {
  "allowFontScaling": undefined,
  "children": "Albums",
  "onLayout": [Function anonymous],
  "style": undefined,
  "tintColor": undefined,
}

【问题讨论】:

    标签: reactjs react-native expo react-navigation


    【解决方案1】:

    你可以这样传递道具:

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

    【讨论】:

    • 谢谢!我认为如果我们使用options={({ route }) =&gt; ({ title: route.params.name })} 方式,我们就无法添加其他选项,这就是headerTitle: (props) =&gt; &lt;AlbumTitle {...props} /&gt;,options 中存在的原因。愚蠢的我,你的代码完美运行。
    【解决方案2】:

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

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

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

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

    【讨论】:

    • 是的,我之前已经尝试过上面的示例并且它运行良好,没有 AlbumTitle 组件。但是如果我使用它,我该如何添加其他选项,如headerStyle
    猜你喜欢
    • 1970-01-01
    • 2018-02-26
    • 2020-10-04
    • 2018-07-29
    • 2020-01-09
    • 2019-02-07
    • 1970-01-01
    • 2021-09-16
    • 1970-01-01
    相关资源
    最近更新 更多