在react-native中找不到变量itemData

时间:2019-12-03 12:23:32

标签: javascript react-native

代码:

import React, { useState } from 'react';
import { StyleSheet, Text, View, Button, TextInput, ScrollView, FlatList } from 'react-native';

import GoalItem from './components/GoalItem';

export default function App() {
    const [enteredGoal, setEnteredGoal] = useState('');

    const [courseGoals, setCourseGoals] = useState([]);


    const goalInputHandler = (enteredText) => {

        setEnteredGoal(enteredText);
    };


    const addGoalHandler = () => {

        //console.log(enteredGoal);

        setCourseGoals(currentGoals => [...currentGoals, { id: Math.random().toString(), value: enteredGoal }]);
    };
    return (

        <View style={styles.screen}>
            <View style={styles.inputContainer}>

                <TextInput placeholder="Course Goal" style={styles.input}
                    onChangeText={goalInputHandler} value={enteredGoal} />
                <Button title="Add" onPress={addGoalHandler} />

            </View>
            <FlatList keyExtractor={(item, index) => item.id} data={courseGoals}
                renderItem={itemData => <GoalItem title={itemData.item.value} />}



            />


        </View>

    );
}

const styles = StyleSheet.create({

    screen: {
        padding: 50
    },
    inputContainer: {
        flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center'

    },

    input: {

        width: '70%', borderBottomColor: 'black', borderWidth: 1, padding: 10
    },

});

GoalItem组件:

import React from 'react';

import { View, Text, StyleSheet } from 'react-native';

const GoalItem = props => {

    return (
        <View style={styles.listItem}>
            <Text>{props.title}</Text>
        </View>
    );


};

const styles = StyleSheet.create({

    listItem: {

        padding: 10, backgroundColor: '#ccc', borderColor: 'black', borderWidth: 1, marginVertical: 10

    }


});
export default GoalItem;
  

错误:下面是代码,请检查找不到变量itemData   在本机

请问我是React-native的新手,我只待了大约两个小时。任何 帮助将不胜感激。提前致谢。查看代码并分享一些建议,以使代码正常工作。

谢谢:)

2 个答案:

答案 0 :(得分:1)

应该是

<FlatList keyExtractor={(item, index) => item.id} 
          data={courseGoals}
          renderItem={(itemData) => <GoalItem title={itemData.item.value} }/>

<FlatList keyExtractor={(item, index) => item.id} 
          data={courseGoals}
          renderItem={({item}) => <GoalItem title={item.value} }/>

答案 1 :(得分:1)

应该是这样的:

<FlatList 
       data={courseGoals}
       renderItem={itemData => (
         
        <View  style={styles.listItem}>
          <Text>{itemData.item}</Text>
          </View>  
          )}
          />