可以在React导航的标题标题中访问整个Redux状态吗?
official docs说对应于导航的状态是可访问的:
static navigationOptions = {
title: ({ state }) => `Chat with ${state.params.user}`
};但我希望访问Redux状态的其他部分,当状态更新时标题也会更新。这在今天有可能吗?
发布于 2017-06-30 20:41:11
这可以通过一些解决方法来实现。我甚至不认为这是一种解决办法,我也认为这是一个很棒的功能:-)
你只需要在你的头中使用一个新的组件,如下所示:
static navigationOptions = {
header: (navigation) => {
return <HomeViewTitle />;
}
}然后,您可以使用redux状态连接到我的示例HomeViewTitle:
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);然后,在HomeViewTitle中将redux状态设置为道具,并且可以将标头设置为动态
发布于 2018-08-17 02:29:29
保留header组件样式的一种更简单的方法是利用React-Navigation的getParam and 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 })
}确保将标题发送给props
const mapStateToProps = state => {
return {
title: state.titleSavedInState,
}
};如果您在组件的状态再次更新之前没有对状态进行任何更改(请注意,在redux中更新状态只会更新组件的道具),上述操作就足够了。但是,如果您要在组件打开时进行更改,则还需要使用:
componentWillUpdate(nextProps, nextState){
if(this.props.navigation.getParam('title', 'DEFAULT') != this.props.titleSavedInState)
this.props.navigation.setParams({ 'title': this.props.titleSavedInState })
}https://stackoverflow.com/questions/42998253
复制相似问题