ama*_*iny 14 react-native redux react-navigation
是否可以在React Navigation的标题标题中访问整个Redux状态?
在官方的文档说,对应导航状态是可访问:
static navigationOptions = {
title: ({ state }) => `Chat with ${state.params.user}`
};
Run Code Online (Sandbox Code Playgroud)
但我希望访问我的Redux状态的其他部分,当状态更新时标题更新.今天有可能吗?
采取一些解决方法是可行的。我什至都不会将此称为解决方法,也不会将其称为一个很棒的功能:-)
您只需要在标题中使用一个新组件,如下所示:
static navigationOptions = {
header: (navigation) => {
return <HomeViewTitle />;
}
}
Run Code Online (Sandbox Code Playgroud)
然后可以在我的案例中将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);
Run Code Online (Sandbox Code Playgroud)
然后将您的redux状态作为HomeViewTitle中的props,您可以将标头设置为动态
保留标题组件样式的更简单方法是使用React-Navigation getParam和setParams.在navigationOptions你有:
static navigationOptions = ({ navigation }) => {
return {
title: navigation.getParam('title', 'DEFAULT VALUE IF PARAM IS NOT DEFINED'),
};
}
Run Code Online (Sandbox Code Playgroud)
然后componentWillMount()你会有:
componentWillMount(){
this.props.navigation.setParams({ 'title': this.props.title })
}
Run Code Online (Sandbox Code Playgroud)
确保将标题发送给道具
const mapStateToProps = state => {
return {
title: state.titleSavedInState,
}
};
Run Code Online (Sandbox Code Playgroud)
如果您没有对组件状态之前的状态进行任何更改(请注意,在redux中更新状态仅更新组件的支持)再次更新,则上述操作就足够了.但是,如果要在组件打开时进行更改,还需要使用:
componentWillUpdate(nextProps, nextState){
if(this.props.navigation.getParam('title', 'DEFAULT') != this.props.titleSavedInState)
this.props.navigation.setParams({ 'title': this.props.titleSavedInState })
}
Run Code Online (Sandbox Code Playgroud)