在React Native中有条件地渲染标头

时间:2020-06-10 10:00:48

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

嗨,我正在尝试根据状态呈现标题。如果状态等于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>
          )
        };
    };

1 个答案:

答案 0 :(得分:0)

您应该考虑将导航更新为新版本。

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

代码应类似于以下内容,您可以在解决方案中采用

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