是否可以在 React Navigation 的标题标题中访问整个 Redux 状态?
官方文档说导航对应的状态是可以访问的:
static navigationOptions = {
title: ({ state }) => `Chat with ${state.params.user}`
};
但我希望访问我的 Redux 状态的其他部分,并在状态更新时更新标题。今天有可能吗?
是否可以在 React Navigation 的标题标题中访问整个 Redux 状态?
官方文档说导航对应的状态是可以访问的:
static navigationOptions = {
title: ({ state }) => `Chat with ${state.params.user}`
};
但我希望访问我的 Redux 状态的其他部分,并在状态更新时更新标题。今天有可能吗?
这可以通过一些解决方法来实现。我什至不会称这是一种解决方法,我会称这是一个很棒的功能:-)
您只需要在标题中使用一个新组件,如下所示:
static navigationOptions = {
header: (navigation) => {
return <HomeViewTitle />;
}
}
然后您可以在我的情况下将 HomeViewTitle 与 redux 状态连接:
import React, { Component } from 'react';
import {
View,
Text
} from 'react-native';
import { connect } from 'react-redux';
class HomeViewTitle extends Component {
render() {
return (
<View style={{height: 64, backgroundColor: '#000000', alignItems: 'center', justifyContent: 'center', paddingTop: 20}}>
<Text style={{color: '#FFFFFF', fontSize: 17, fontWeight: 'bold'}}>Home</Text>
</View>
);
}
}
const mapStateToProps = (state) => {
return state;
}
export default connect(mapStateToProps)(HomeViewTitle);
然后你有你的 redux 状态作为 HomeViewTitle 中的道具,你可以设置标题动态
保留标题组件样式的更简单方法是使用 React-NavigationgetParam
和setParams
. 在navigationOptions
你会有:
static navigationOptions = ({ navigation }) => {
return {
title: navigation.getParam('title', 'DEFAULT VALUE IF PARAM IS NOT DEFINED'),
};
}
然后componentWillMount()
你会有:
componentWillMount(){
this.props.navigation.setParams({ 'title': this.props.title })
}
确保将标题发送到道具
const mapStateToProps = state => {
return {
title: state.titleSavedInState,
}
};
如果在组件的状态(注意在 redux 中更新状态只更新组件的 props)再次更新之前,您没有对状态进行任何更改,以上就足够了。但是,如果您要在组件打开时进行更改,您还需要使用:
componentWillUpdate(nextProps, nextState){
if(this.props.navigation.getParam('title', 'DEFAULT') != this.props.titleSavedInState)
this.props.navigation.setParams({ 'title': this.props.titleSavedInState })
}