【问题标题】:Change header text dynamically in React Native在 React Native 中动态更改标题文本
【发布时间】:2018-04-02 11:49:06
【问题描述】:

我的 StackNavigator 的 navigationOptions 是:--

static navigationOptions = ({navigation}) => {
    return ({
        headerRight: (
            (navigation.state.params.actionTitle)?
                <TouchableOpacity style={{padding: 10}} onPress={() => navigation.state.params.onPressDelete()}>
                    <Text style={{
                        fontSize: 16,
                        color: Colors.primaryText
                    }}>{navigation.state.params.actionTitle}</Text>
                </TouchableOpacity>:null
        )
    })
};

navigation.state.params.actionTitle 默认未定义。所以在页面上它不会显示 headerRight 视图。我想根据 redux 的一些网络响应显示 headerRight 视图。我正在处理 componentWillReceiveProps 部分中的 redux 数据。

但是从 componentWillReceiveProps 如果我尝试更改 actionTitle 则会发生递归并且整个 UI 被阻塞。通过递归,我的意思是 componentWillReceiveProps 被重复调用。我正在使用以下方式设置导航状态:--

componentWillReceiveProps(props){
  this.props.navigation.setParams({
        actionTitle : "Delete"
  });
}

我在这里做错了什么?

【问题讨论】:

    标签: react-native


    【解决方案1】:

    componentWillReceiveProps 会在每个状态和 props 更改时调用,这就是为什么它会重新渲染多次。尝试根据您的网络响应更新导航标题。

    检查标题更改的道具,如果道具包含网络响应,则仅更新标题,即在您的情况下删除。

    if(props.header === "Delete") {  // assuming you are passing as header in redux
      this.props.navigation.setParams({
        actionTitle : "Delete"
      });
    }
    

    【讨论】:

      【解决方案2】:

      你可以尝试制作一个自定义组件,像这样连接redux

      // Header.js
      import { connect } from 'react-redux'
      import React from 'react'
      import {View, Text} from 'react-native'
      
          const Header = ({name}) => {
              return (
                  <View  style={{alignItems: 'center', justifyContent: 'center'}}>
                      <Text>{name}</Text>
                  </View>
              )
          }
      
          // REDUX MAPPING
          const mapStateToProps = state => ({
              name: state.auth.name
          })
      
          export default connect(mapStateToProps, null)(Header);
      

      并在你的组件中使用它

      import Header from '../../Components/Header'
      
      // Inside your class
      
       static navigationOptions = ({ navigation }) => {
              return {
                  headerRight: <Header />,
              }
          }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-10-09
        • 1970-01-01
        • 2018-09-12
        • 2019-03-10
        • 2017-08-08
        • 1970-01-01
        • 2021-01-30
        • 1970-01-01
        相关资源
        最近更新 更多