Configuring Headers - 配置导航条
译注:下文中将
Header统一翻译为导航条。
导航条仅适用于StackNavigator。
在前面的例子中,我们在应用里创建了一个StackNavigator来显示几个页面。
当跳转到Chat页面时,可以在navigate函数中为新route传入指定参数。因此,我们可以为Chat页面传递聊天对象的名字。
this.props.navigation.navigate('Chat', { user: 'Lucy' });
这个user参数可以在Chat页面被获取:
class ChatScreen extends React.Component {render() {const { params } = this.props.navigation.state;return <Text>Chat with {params.user}</Text>;}}
设置导航条标题
下一步,使用页面的参数来设置导航条的标题:
class ChatScreen extends React.Component {static navigationOptions = ({ navigation }) => ({title: `Chat with ${navigation.state.params.user}`,});...}

添加一个右侧按钮
接下来,我们添加一个navigationOptions对象,可以为header添加一个自定义的右侧按钮:
static navigationOptions = {headerRight: <Button title="Info" />,...

可以使用navigation prop来定义navigationOptions。让我们来根据route的参数渲染不同的按钮,并设置当按钮按下时调用navigation.setParams函数。
static navigationOptions = ({ navigation }) => {const { state, setParams } = navigation;const isInfo = state.params.mode === 'info';const { user } = state.params;return {title: isInfo ? `${user}'s Contact Info` : `Chat with ${state.params.user}`,headerRight: (<Buttontitle={isInfo ? 'Done' : `${user}'s info`}onPress={() => setParams({ mode: isInfo ? 'none' : 'info' })}/>),};};
现在,导航条可以与页面的route/state进行交互:

导航条与页面组件进行交互
有时候,导航条需要访问页面组件的属性,例如函数或状态。
比如说,我们想创建一个“编辑联系人信息”的页面,在导航条上有一个保存按钮,我们希望当保存信息时,用一个ActivityIndicator来代替保存按钮。
class EditInfoScreen extends React.Component {static navigationOptions = ({ navigation }) => {const { params = {} } = navigation.state;let headerRight = (<Buttontitle="Save"onPress={params.handleSave ? params.handleSave : () => null}/>);if (params.isSaving) {headerRight = <ActivityIndicator />;}return { headerRight };};state = {nickname: 'Lucy jacuzzi'}_handleSave = () => {// Update state, show ActivityIndicatorthis.props.navigation.setParams({ isSaving: true });// Fictional function to save information in a store somewheresaveInfo().then(() => {this.props.navigation.setParams({ isSaving: false});})}componentDidMount() {// We can only set the function after the component has been initializedthis.props.navigation.setParams({ handleSave: this._handleSave });}render() {return (<TextInputonChangeText={(nickname) => this.setState({ nickname })}placeholder={'Nickname'}value={this.state.nickname}/>);}}
注:由于handleSave参数仅在组件安装时设置,因此不能立即在navigationOptions函数中使用。在设置handleSave之前,为了立即渲染并避免闪烁,我们给Button组件传递一个空的函数。
