简体   繁体   中英

Dynamically render component for each item in array React Native

Beginner question here, not sure exactly what this would be considered, but I'm trying to make a form where a user can add and remove input rows upon pressing a button. What do I need to change to render new components or remove components when the Add or Remove buttons are pressed? Right now, the Add and Remove button change the textInput array appropriately, but components are not actually being added or removed.

Here is my current code:

FormScreen.js

import React from 'react';
import { View, StyleSheet, ScrollView } from 'react-native';
import { Button, Caption } from 'react-native-paper';
import InputCard from '../components/InputCard';

const FormScreen = props => {
    const textInput = [1,2,3];

    const addTextInput = () => {
        let currArr = textInput;
        let lastNum = currArr[currArr.length -1]
        let nextNum = lastNum + 1
        console.log(currArr, lastNum, nextNum);
        textInput.push(
            nextNum
        );
        
        console.log(textInput);
    };
    
    const removeTextInput = () => {
        textInput.pop();
        console.log(textInput);
    };

    return (
        <ScrollView>
            <View style={styles.col}>
                <View style={styles.row}>
                    <Caption>Favorite colors?</Caption>
                </View>
                <View style={styles.row}>
                    <View>
                    {textInput.map(key => {
                        return (
                            <InputCard key={key}/>
                        );
                    })}
                    </View>
                </View>
                <View>
                    <View style={styles.col}>
                        <Button title='Add' onPress={() => addTextInput()}>Add</Button>
                    </View>
                    <View style={styles.col}>
                        <Button title='Remove' onPress={() => removeTextInput()}>Remove</Button>
                    </View>
                </View>
            </View>
        </ScrollView>
    );
};

export default FormScreen;

InputCard.js

import React, { useState } from "react";
import { View, StyleSheet } from 'react-native';
import { Caption, Card, TextInput } from "react-native-paper";

const InputCard = (props) => {

    const [input, setInput] = useState('');
    
    return (
        <View>
            <Card>
                <Card.Content>
                    <Caption>Item {props.key}</Caption>
                    <View style={styles.row}>
                        <View style={styles.half}>
                            <TextInput
                                label="Input"
                                value={input}
                                onChangeText={input => setInput(input)}
                                mode="outlined"
                                style={styles.textfield}
                            />
                        </View>
                    </View>
                </Card.Content>
            </Card>
        </View>
    );
}

export default InputCard;

Instead of storing it in a array, try to do something like this, using 2 states.

const [totalTextInput, setTotalTextInput] = useState([])//initial state, set it to any data you want.
const [count, setCount] = useState(0);

const addTextInput = () => {
  
      setCount((prevState) => prevState + 1);
      setTotalTextInput((prevState) => {
        const newTextInput = Array.from(prevState);  // CREATING A NEW ARRAY OBJECT
        newTextInput.push(count);
        return newTextInput;  
      });
    };

const removeTextInput = () => {
  setTotalTextInput((prevState) => {
    const newTextInput = Array.from(prevState);  // CREATING A NEW ARRAY OBJECT
    newTextInput.pop();
    return newTextInput;  
  });
};

And in your code:

<View>
      {totalTextInput.map(key => {
           return (
                <InputCard key={key}/>
            );
       })}
</View>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM