You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native点击用户后根据用户类型切换Modal内容的实现问题

实现方案

你可以直接使用React JSX的条件渲染语法实现需求,只需要把原来的两个View块通过判断user.type的值来动态渲染即可,修改后的核心代码如下:

interface IModalProps {
    onPressClose: () => void;
    user: IUser | null;
    onPressNavigate: () => void;
}

export const UserInfoModal = (props: IModalProps) => {
    const { onPressClose, user, onPressNavigate } = props;
    const { width, height } = useWindowDimensions();
    const landscape = width > height;

    return (
        <Modal animationType='slide' visible={!!user} transparent={true}>
            {/* 根据用户类型动态渲染对应视图 */}
            {user.type === type.Renter ? (
                <View style={[styles.mainContainer, globalStyles.Shadow, { width: isTablet() ? '70%' : '80%' }]}>
                    <WZCircleButton onPress={onPressClose} style={styles.closeButton} iconUri={require('@assets/icons/close-button.png')} />
                    <View>
                        <WZText style={styles.headerTitle}>{user?.displayName}</WZText>
                        <WZText style={styles.title}>{Strings.ChatScreen.SchoolStreet}</WZText>
                        <WZUserAvatar style={styles.userAvatar} size={150} user={user} />
                        <WZText style={styles.subTitle}>{Strings.ChatScreen.ProfileText}</WZText>
                        <WZButton onPress={onPressNavigate} text='Start Chat' style={styles.buttonStartChat} />
                    </View>
                </View>
            ) : (
                <View style={[styles.mainContainer, globalStyles.Shadow, { width: isTablet() ? '70%' : '80%' }]}>
                    <WZText style={styles.headerTitleConsultant}>{Strings.ChatScreen.SearchByResidentByFirstName}</WZText>
                    <View>
                        <WZText>{Strings.ChatScreen.Email}</WZText>
                        <WZText>{Strings.ChatScreen.EmailInfo}</WZText>
                        <WZButton style={styles.buttonStartChat} text={Strings.ChatScreen.EmailButton}></WZButton>
                    </View>
                    <View>
                        <WZText>{Strings.ChatScreen.WalkInHours}</WZText>
                        <WZText>{Strings.ChatScreen.WalkInHoursInfo}</WZText>
                    </View>
                </View>
            )}
        </Modal>
    );
};

注意事项

  • 请确保当前文件已经正确导入type枚举,否则会出现未定义报错
  • 由于Modal的visible属性仅在user不为空时为true,所以条件判断时无需额外处理user为空的情况,如果你需要更高的代码健壮性,可以把判断条件改为user?.type === type.Renter
  • 如果后续需要扩展更多用户类型的自定义视图,建议把渲染逻辑抽成独立函数,用switch或者对象映射的方式处理,代码可维护性会更好

内容的提问来源于stack exchange,提问作者Manko

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 04:36:04