【问题标题】:React-Navigation: Use/Change header title with Redux stateReact-Navigation:使用/更改带有 Redux 状态的标题标题
【发布时间】:2017-03-24 11:22:48
【问题描述】:

是否可以在 React Navigation 的标题标题中访问整个 Redux 状态?

official docs 表示导航对应的状态是可访问的:

  static navigationOptions = {
    title: ({ state }) => `Chat with ${state.params.user}`
  };

但我希望访问我的 Redux 状态的其他部分,并在状态更新时更新标题。今天可以吗?

【问题讨论】:

  • react-helmet 连接到 redux 怎么样?

标签: react-native redux react-navigation


【解决方案1】:

这可以通过一些解决方法来实现。我什至不会称其为解决方法,也不会称其为很棒的功能:-)

您只需在标题中使用一个新组件,如下所示:

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 中的道具,你可以设置标题动态

【讨论】:

  • 所以可以在标题中放置图像、按钮等吗?渲染效果如何?
  • 是的,基本上所有内容都可以放在标题中。它的渲染方式与其他所有 redux 连接组件的渲染方式相同。就我而言,我在标题中有一个图像,该图像在应用程序启动时不可用。加载应用程序后,它会发出 json 请求并将图像加载到 redux 存储中。当图像在商店中时,它会更新 HeaderViewTitle 并显示图像
  • 但是,使用这种方法,您将失去所有使用 react-navigation 开箱即用的自动平台样式功能。 :(
  • 您指的是哪种样式?要么你想使用 react-navigation 的默认值,要么自己做,只要让你的组件看起来像你想要的那样
【解决方案2】:

保留标题组件样式的更简单方法是使用 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 })
}

确保将标题发送到道具

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 })
}

【讨论】:

  • 嘿,我想在下一个屏幕中使用传递的参数,我尝试使用 ``` static navigationOptions = ({ navigation }) => { return { title: navigation.getParam ('providerName'), }; } render() { return ( Provider Profile {console.log("@name", this.props.navigation.getParam('providerName'))} // 我可以在这里得到名字 ); } ```
猜你喜欢
  • 1970-01-01
  • 2017-08-08
  • 2019-03-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-28
  • 1970-01-01
  • 2021-06-28
相关资源
最近更新 更多