How to loop and render elements in React-native?

后端 未结 4 593
粉色の甜心
粉色の甜心 2020-12-24 04:28

Is it possible to loop an identical component in Render function?

Something like this:

...

onPress = () => {
 ...
};

initialArr = [[\"blue\",\"t         


        
4条回答
  •  时光说笑
    2020-12-24 05:30

    For initial array, better use object instead of array, as then you won't be worrying about the indexes and it will be much more clear what is what:

    const initialArr = [{
        color: "blue",
        text: "text1"
    }, {
        color: "red",
        text: "text2"
    }];
    

    For actual mapping, use JS Array map instead of for loop - for loop should be used in cases when there's no actual array defined, like displaying something a certain number of times:

    onPress = () => {
        ...
    };
    
    renderButtons() {
        return initialArr.map((item) => {
            return (
                
            );
        });
    }
    
    ...
    
    render() {
        return (
            
                {
                    this.renderButtons()
                }
            
        )
    }
    

    I moved the mapping to separate function outside of render method for more readable code. There are many other ways to loop through list of elements in react native, and which way you'll use depends on what do you need to do. Most of these ways are covered in this article about React JSX loops, and although it's using React examples, everything from it can be used in React Native. Please check it out if you're interested in this topic!

    Also, not on the topic on the looping, but as you're already using the array syntax for defining the onPress function, there's no need to bind it again. This, again, applies only if the function is defined using this syntax within the component, as the arrow syntax auto binds the function.

提交回复
热议问题