# 配置导航器的header

2017-02-13  本文已影响96人  sunner168

配置导航器的header

在前面的例子中,我们创建了一个栈导航器去展示几个场景/页面用于在我们的应用中。

当我们跳转到聊天页面中,我们可以在navigate函数中指定一些参数用在新的路由中。这里我们将提供一个人名去聊天页面:

this.props.navigation.navigate('Chat', { user:  'Lucy' });

The user param can be accessed from the chat screen:

class ChatScreen extends React.Component {
  render() {
    const { params } = this.props.navigation.state;
    return <Text>Chat with {params.user}</Text>;
  }
}

设置header的标题

Next, the header title can be configured to use the screen param:
下一步,我们可以在页面配置的参数中设置头标题:

class ChatScreen extends React.Component {
  static navigationOptions = {
    // // Title may be a simple string:
    // title: 'Hello',

    // Or the title string may be a function of the navigation prop:
    title: ({ state }) => `Chat with ${state.params.user}`
  };
  ...
}
basic-header

在右边添加一个按钮

Then we can add a header navigation option that allows us to add a custom right button:

我们可以在header添加一个header的导航选项让我们自定义一个右边的按钮。

static navigationOptions = {
  header: {
    right: <Button title="Info" />,
  },
  ...
header-button

就跟title选项一样,header中的选项都可以定义为函数,函数中可以使用navigation prop导航栏传递的一些参数。
让我们基于路由传递的参数渲染出不同的按钮同时设置通过按钮去调用navigation.setParams 去传递。

static navigationOptions = {
  title: ({ state }) => {
    if (state.params.mode === 'info') {
      return `${state.params.user}'s Contact Info`;
    }
    return `Chat with ${state.params.user}`;
  },
  header: ({ state, setParams }) => {
    // The navigation prop has functions like setParams, goBack, and navigate.
    let right = (
      <Button
        title={`${state.params.user}'s info`}
        onPress={() => setParams({ mode: 'info' })}
      />
    );
    if (state.params.mode === 'info') {
      right = (
        <Button
          title="Done"
          onPress={() => setParams({ mode: 'none' })}
        />        
      );
    }
    return { right };
  },
  ...

Now, the header can interact with the screen route/state:
现在页面header部分的内容可以互相影响了。

header-interaction

可以到这里去了解其余header选项。

上一篇 下一篇

猜你喜欢

热点阅读