【问题标题】:Render conditionally header in react native在本机反应中有条件地渲染标题
【发布时间】:2020-06-10 18:43:52
【问题描述】:

您好,我正在尝试根据状态呈现标题。如果状态等于 true,我将显示头像图像,如果为 false,我将呈现默认徽标。我尝试过基于三元运算符执行此操作,但它不起作用。这是代码:

static navigationOptions = ({navigation}) => {
        const { params } = navigation.state;
        return {
          headerTitle: () => (
            <View style ={{alignItems: 'center', justifyContent: 'center',flex:1, flexDirection:'column', overflow:'visible'}}>
                 {this.state.Loaded == false ?
                    <View style ={{alignItems: 'center', justifyContent: 'center',flex:1, flexDirection:'column', overflow:'visible'}}> 
                        <Text style={{marginBottom:15,fontSize:20,fontWeight:"900", color:'#000' }}>Pseudo</Text>
                        <Image
                            style = {styles.avatar}
                            source = {require('../../../Assets/avatar.jpg')} />
                    </View>
                    :
                    <View style={[styles.bandeauHeader, {  } ]}>
                    <Text style={styles.textHeader}>Aide</Text>
                    <Image source={GlobalInclude.LogoIconRose} style={styles.logoBandeauHeader} />
                    </View>
                }      
            </View>
          )
        };
    };

【问题讨论】:

  • 你用的是什么版本的 react-navigation ?
  • 我使用的是 2.14.2
  • 如果可能,您应该考虑使用更新的 react 导航版本 - 2.14 似乎很旧。
  • @SauceCurry 你试过我的答案了吗?

标签: react-native conditional-statements react-navigation


【解决方案1】:

您应该考虑将导航更新到较新的版本。

首先状态在静态函数中不可用,因此您必须使用导航参数来更新标题。

代码应该类似于下面的代码,您可以在解决方案中采用。

class DetailsScreen extends React.Component {
  state = {
    flag: true,
  };

  static navigationOptions = ({ navigation }) => {
    return {
      headerTitle: navigation.getParam('flag') ? (
        <Text>12323231321</Text>
      ) : (
        <Text>67676777</Text>
      ),
    };
  };

  render() {
    const { navigation } = this.props;

    return (
      <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
        <Text>Details Screen</Text>

        <Button
          title="Update the title"
          onPress={() =>
            this.setState({ flag: !this.state.flag }, () =>
              this.props.navigation.setParams({ flag: this.state.flag })
            )
          }
        />
      </View>
    );
  }
}

【讨论】:

    猜你喜欢
    • 2017-04-26
    • 2019-04-04
    • 2018-01-25
    • 2017-05-09
    • 1970-01-01
    • 2020-04-09
    • 2020-03-15
    • 1970-01-01
    • 2022-08-15
    相关资源
    最近更新 更多