将本地变量传递给React Native中的组件

时间:2020-11-06 11:31:40

标签: javascript react-native

我正在构建待办事项列表应用程序,我想长按各个待办事项,将其颜色更改为绿色,以将其标记为已完成。

我的App.js中有一个var color = 'white';,还有另一个名为listItem的列表项组件。

我具有更改颜色的基本功能

const longPressHandler = () => {
    (color == 'white') ? color = 'green' : color = 'white';
  }

我正在通过listItem的道具发送color

<ListItem item={item} longPressHandler = {longPressHandler} color={color} pressHandler = {pressHandler}/>

我正在按如下方式backgroundColor: props.color使用它:

const styles = StyleSheet.create({
        listItem:{
            padding: 8,
            margin:4,
            fontSize: 18,
            textAlignVertical:'center',
            borderColor:'gray',
            borderWidth: 3,
            borderStyle: 'solid',
            borderRadius:10,
            backgroundColor: props.color,
          }
    })

BUUT,它不起作用...我在做什么错?有没有我错过的简单解决方案...

这是App.js的完整代码

import React, {useEffect, useState} from 'react';
import {Text, View, StyleSheet, FlatList, Alert, TouchableWithoutFeedback, Keyboard, Button, AsyncStorage } from 'react-native';
import ListItem from './components/listItem';
import AddItem from './components/addItem';

// npx react-native start // TO START
// npx react-native run-android // TO PROJECT INTO EMULATOR

//Hooks cant be used in class components, thus, switched from Class component structure => Function component structure

export default function TODOList() {

  const [todos, setTodos] = useState([
    {todo: 'do chores', key: '1'},
    {todo: 'do homework', key: '2'},
    {todo: 'go to grocery', key: '3'},
  ]);
 

  var color = 'white';

  //This handler DELETES the pressed list item from the list
  const pressHandler = (key) => {
    const newtodos = todos.filter(todo => todo.key != key);

    setTodos(newtodos);
    
    
  }

  //ADDS a new todo with the given text and a randomly generated key to the old todos list
  const inputSubmitHandler = (text) => {

    if(text.length > 0){
      const key = Math.random().toString();
      const newTodos = [{text, key}, ...todos];

      setTodos(newTodos);
      
    }else{
      Alert.alert('ERROR!', 'Text cannot be empty', [{text:'OK'}])
    }
  }

  //TODO Change color of the individual item in the list
  const longPressHandler = () => {
    (color == 'white') ? color = 'green' : color = 'white';
  }

      
  console.log('color', color);
  return (
    <TouchableWithoutFeedback onPress={() => {Keyboard.dismiss();}}>
      <View style={styles.mainPage}>
        <View style = {styles.header}>
            <Text style={styles.title}>TODO List</Text>
        </View>
        <View style={styles.content}>
          <AddItem inputSubmitHandler={inputSubmitHandler} />
          <View style={styles.list}>
            <FlatList
              data={todos}
              renderItem={( {item} ) => (
                <ListItem item={item} longPressHandler = {longPressHandler} color={color} pressHandler = {pressHandler}/>
              )}
            />
          </View>
        </View>
      </View>
    </TouchableWithoutFeedback>
  );
}

//The margins, paddings, etc. are given as pixel values, wont work same in other devices.
const styles = StyleSheet.create({
  mainPage: {
    flex: 1, // takes the whole background
    backgroundColor: 'white',
  },
  content: {
    flex: 1,
  },
  list:{
    margin: 10,
    flex:1,
  },
  header:{
    height: 50,
    paddingTop: 8,
    backgroundColor: 'orange'
},
  title:{
    textAlign: 'center',
    fontSize: 24,
    fontWeight: 'bold',
},
});

这是listItem.js的完整代码

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

export default function ListItem(props) {

    //Moved the style inside of the function since I want to use the color prop in 'backgroundCcolor'
    const styles = StyleSheet.create({
        listItem:{
            padding: 8,
            margin:4,
            fontSize: 18,
            textAlignVertical:'center',
            borderColor:'gray',
            borderWidth: 3,
            borderStyle: 'solid',
            borderRadius:10,
            backgroundColor: props.color,
          }
    })

    return (
        <TouchableOpacity onLongPress={() => props.longPressHandler()} onPress = {() => props.pressHandler(props.item.key)}>
              <Text style={styles.listItem}> {props.item.todo}</Text> 
        </TouchableOpacity>
    
    )
}

0 个答案:

没有答案