You need to enable JavaScript to run this app. React Native使用TouchableWithoutFeedback无内容、用View正常是什么原因
优惠活动
大模型
产品
解决方案
定价
更多

React Native使用TouchableWithoutFeedback无内容、用View正常是什么原因

问题原因

  • 你代码中给TouchableWithoutFeedback绑定的flex:1等布局样式不会生效:该组件无论是React Native原生版本还是react-native-gesture-handler提供的版本,都不支持直接接收style属性,导致外层容器没有宽高,内部内容自然无法渲染展示。而View组件原生支持style属性,替换后布局规则生效,内容可以正常显示。
  • 补充说明:TouchableWithoutFeedback的核心作用仅为监听触摸事件,本身不参与布局渲染,所有布局相关的属性都需要绑定到它的直接子元素上。

修复方案

将原绑定在TouchableWithoutFeedback上的样式,转移到它内部新增的一层View容器上即可,修改后的代码如下:

import { StatusBar } from 'expo-status-bar';
import React, { useState, useEffect } from 'react';
import { StyleSheet, Text, View, ImageBackground, TextInput, Dimensions, KeyboardAvoidingView, Keyboard } from 'react-native';
import { TouchableOpacity, ScrollView, TouchableWithoutFeedback } from 'react-native-gesture-handler';
import { Ionicons } from '@expo/vector-icons';

const width = Dimensions.get('window').width;
const height = Dimensions.get('window').height;

const createRoom = () => {
  return (
    <TouchableWithoutFeedback onPress={() => Keyboard.dismiss()}>
      {/* 原外层样式转移到这里的View上 */}
      <View style={{flex: 1,alignItems: 'center', justifyContent: 'center'}}>
        <KeyboardAvoidingView behavior="position">
          <View style={{backgroundColor: 'red', width: width * 0.8, padding: 20, borderRadius: 8, elevation: 2}}>
            <View style={{marginTop: 20, marginBottom: 20}}>
              <TextInput placeholder="Username" style={styles.input} />
            </View>
            <View style={styles.locationContainer}>
              <TouchableOpacity>
                <Text>geolocation</Text>
              </TouchableOpacity>
              <View>
                <Text>Test</Text>
              </View>
            </View>
            <TouchableOpacity style={styles.button}>
              <Text>Gruppe erstellen</Text>
            </TouchableOpacity>
          </View>
        </KeyboardAvoidingView>
      </View>
    </TouchableWithoutFeedback>
  )
};

const styles = StyleSheet.create({
  container: {
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#fff'
  },
  input: {
    padding: 4,
    backgroundColor: '#fff',
  },
  image: {
    height: 150,
    borderRadius: 12,
  },
  locationContainer: {
    flexDirection: 'row',
    justifyContent: 'space-between'
  },
  button: {
    color: '#fff',
    justifyContent: 'center',
    alignItems: 'center',
    padding: 10
  }
});

export default createRoom;

注:上述代码额外新增了点击空白处收起键盘的逻辑,符合该组件的常规使用场景,不需要可自行删除。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.20 19:06:04