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

React Native待办应用添加内容后仅显示样式框无文字问题求助

问题原因
  • 核心问题是TextInput的取值逻辑错误:React Native 框架的TextInput组件和Web端的input元素逻辑不同,你写的onChange={(e) => setText(e.target.value)}是Web端的写法,在React Native里无法正确拿到输入的内容,导致text状态始终为空,添加到待办列表items里的内容也都是空值,自然渲染不出来文字。
  • 样式冗余问题(不影响显示,可优化):你给Text类型的item样式加了display: 'flex'、flexDirection: 'column'属性,React Native里所有元素默认都是flex布局,且Text组件不支持flexDirection属性,属于无效冗余代码。
修复方案
  1. 把TextInput的onChange替换为React Native专用的onChangeText属性,直接拿到输入的字符串值,修改后的代码如下:
<TextInput
  style={styles.input}
  value={text}
  onChangeText={(inputVal) => setText(inputVal)}
/>

如果你要保留onChange写法,也可以修改取值逻辑为:

onChange={(e) => setText(e.nativeEvent.text)}
  1. 可选择性删除styles.item里的display: 'flex'和flexDirection: 'column'两行无效代码,不影响功能仅做代码优化。
修复后完整代码
import React from 'react'
import { StyleSheet, Text, View, TextInput, Button, Alert } from 'react-native';
import Header from './Components/Header';

const App = () => {

  const [text, setText] = React.useState("");
  const [items, setItems] = React.useState([])


  const addTodo = () => {
    if (text == "") {
      alert("Please Enter Todo");
    }
    else {
      setItems([...items, text]);
      setText('');
    }
  }

  return (
    <View>
      <Header />
      <TextInput
        style={styles.input}
        value={text}
        onChangeText={(inputVal) => setText(inputVal)}
      />
      <Button title="Add +"
        onPress={addTodo}
      />
      <View style={styles.list}>
        {
          items.map((elem, ind) => {
            return (
              <View key={ind}>
                <Text style={styles.item}>{elem}</Text>
              </View>
            )
          })
        }
      </View>
    </View>
  )
}

export default App

const styles = StyleSheet.create({
  list: {
    marginTop: 20,
    padding: 100,
  },
  item: {
    padding: 20,
    marginTop: 10,
    borderWidth: 1,
    borderStyle: 'dashed',
    borderColor: 'gray',
    textAlign: 'center',
    backgroundColor: 'lightgray',
    fontWeight: 'bold',
    color: 'black',
    fontSize: 20
  },
  input: {
    height: 40,
    margin: 12,
    borderWidth: 1,
    padding: 10,
  },
})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 11:51:02