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

React Native函数式组件中Switch-Case返回View无法正常渲染如何解决

问题原因

  • 你定义的SwitchCase是一个函数,但最终返回时直接返回了SwitchCase函数引用本身,React不会直接渲染函数引用,必须执行函数或者将其作为组件调用才能拿到要渲染的节点。
  • viewKey === ViewKey.HOME_WORKSPACE的分支漏写了return关键字,就算你正确执行了SwitchCase函数,这个分支也只会返回undefined,没有返回要渲染的Card组件。

解决方法

你可以直接去掉多余的SwitchCase函数封装,直接在组件返回逻辑里做判断即可,修正后的参考代码如下:

const LoadingView = ({
    viewKey,
    style,
}: LoadingViewInterface) => {
    if(viewKey === ViewKey.HOME_WORKSPACE) {
        return (
            <Card style={style}>
                <SkeletonBar width={'100%'} height={16} />
                <View style={styles.space}/>
                <SkeletonBar width={'50%'} height={16} />
                <View style={styles.space}/>
                <SkeletonBar width={'50%'} height={16} />
                <View style={styles.space}/>
                <SkeletonBar width={'100%'} height={16} />
            </Card>
        )
    } 
    // 其余分支统一返回undefined即可
    return undefined
};

const styles = StyleSheet.create({
    space: {
        height: 8,
    },
});

export default LoadingView;

如果你要保留SwitchCase函数的写法,需要修改两个地方:一是补上HOME_WORKSPACE分支的return,二是返回时执行函数return SwitchCase()或者以组件形式调用return <SwitchCase />即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 17:15:03