React Native TextInput字段检索未定义的值,并且不在列表屏幕上显示该值

balp4ylt  于 2022-11-17  发布在  React
关注(0)|答案(1)|浏览(107)

我试图在列表中添加一些新项目,但当我在控制台日志上打印列表时,它添加了项目,但显示名称和描述未定义。显然输入有问题,但我不知道原因。此外,在应用程序本身上,它显示添加了新项目,但没有数据。

import React ,{useState}from 'react';
import { KeyboardAvoidingView, StyleSheet,Text,View,TextInput,TouchableOpacity,Keyboard,ScrollView } from 'react-native';
import Task from './components/task';

export default function App(){

  
      const [recipeName,setRecipeName]=useState("");
      const [descriptionItem, setDescriptionItem] = useState("");
      const [items, setItems] = useState([
        { itemName: "Chicken", description: "chicken test", id: 0 }
      ]);
    
  

  

  const handleAddButtonClick = () => {
    
    const newItem = {
      itemName: recipeName, // change
      descriptionItem: descriptionItem,
      id: items.length
    };
    console.log(newItem);
    const newItems = [...items, newItem];

    setItems((state) => {
      console.log(state);
      console.log(newItems);
      return newItems;
    });
    // setRecipeName("");
    // setDescriptionItem("");
    // console.log(items.description);
    // console.log(items.id); //...
  };

 

  return(
    <View style={styles.container}>
    {/* Added this scroll view to enable scrolling when list gets longer than the page */}
    <ScrollView
      contentContainerStyle={{
        flexGrow: 1
      }}
      keyboardShouldPersistTaps='handled'
    >

    {/* Today's Tasks */}
    <View style={styles.tasksWrapper}>
      <Text style={styles.sectionTitle}>Today's tasks</Text>
      <View style={styles.items}>
        {/* This is where the tasks will go! */}
        {
          items.map((item, index) => {
            return (
              <TouchableOpacity key={index}  onPress={() => completeTask(index)}>
                <Text>Recipe {item.itemName}  Description: {item.description}</Text>
                
              </TouchableOpacity>
            )
          })
        }
      </View>
    </View>
      
    </ScrollView>

    {/* Write a task */}
    {/* Uses a keyboard avoiding view which ensures the keyboard does not cover the items on screen */}
    <KeyboardAvoidingView 
      behavior={Platform.OS === "ios" ? "padding" : "height"}
      style={styles.writeTaskWrapper}
    >

<View style={{flexDirection: 'column', flex: 1,  justifyContent: 'center', alignItems: 'center'}}>
      <TextInput style={styles.input} placeholder={'Write a name'} value={recipeName} onChangeText={(text) => setRecipeName(text)} />
      <TextInput style={styles.input} placeholder={'Write a date'} value={descriptionItem} onChange={(text) => setDescriptionItem(text)} />

  </View>

    
      <TouchableOpacity onPress={() => handleAddButtonClick()}>
        <View style={styles.addWrapper}>
          <Text style={styles.addText}>+</Text>
        </View>
      </TouchableOpacity>
    </KeyboardAvoidingView>
    
  </View>
  )
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#E8EAED',
  },
  tasksWrapper: {
    paddingTop: 80,
    paddingHorizontal: 20,
  },
  sectionTitle: {
    fontSize: 24,
    fontWeight: 'bold'
  },
  items: {
    marginTop: 30,
  },
  writeTaskWrapper: {
    position: 'absolute',
    bottom: 60,
    width: '100%',
    flexDirection: 'row',
    justifyContent: 'space-around',
    alignItems: 'center'
  },
  input: {
    paddingVertical: 15,
    paddingHorizontal: 15,
    backgroundColor: '#FFF',
    borderRadius: 60,
    borderColor: '#C0C0C0',
    borderWidth: 1,
    width: 250,
  },
  addWrapper: {
    width: 60,
    height: 60,
    backgroundColor: '#FFF',
    borderRadius: 60,
    justifyContent: 'center',
    alignItems: 'center',
    borderColor: '#C0C0C0',
    borderWidth: 1,
  },
  addText: {},
});
yzuktlbb

yzuktlbb1#

map()函数中迭代项时,请执行以下操作:

items.map((item, index) => {
              return (
                <TouchableOpacity
                  key={index}
                  onPress={() => completeTask(index)}
                >
                  <Text>
                    Recipe {item.itemName} Description: {item.description}
                  </Text>
                </TouchableOpacity>
              );
            })

您使用的状态值不正确。应该是item.descriptionItem,而不是item.description
我还建议你把onChange事件移到单独的方法中,并在其中设置状态,不要使用匿名函数。因此,例如,对于你的描述,它将是这样的:

const handleDescription = (e) => { 
    setDescriptionItem(e.target.value);
};

在JSX中:

<TextInput
        style={styles.input}
        placeholder={"Write a date"}
        value={descriptionItem}
        onChange={handleDescription}
/>

最新消息:
我在sandbox中重新创建了您的代码,并做了一些小的更改:

  • 注解掉Task组件的导入(因为我不知道该组件的功能)
  • 已禁用onPress事件处理程序,因为我无法访问completeTask函数
  • recipeNameonChangeText更改为onChange
  • 已将两个onChange事件提取到不同的方法。
  • items的固定初始状态;它还具有description,而不是descriptionItem

请随意查看。

相关问题