Loop in react-native

前端 未结 6 1652
慢半拍i
慢半拍i 2021-02-04 23:57

I want to make a list of fields depending on the number of the player that user has selected. I wanted to make something like this:

generatePaymentField() {
             


        
6条回答
  •  一个人的身影
    2021-02-05 00:51

    First of all, I recommend writing the item you want to render multiple times (in your case list of fields) as a separate component:

    function Field() {
        return (
            
                
                    
                
                
                    
                
                
                    
                
            
        );
    }
    

    Then, in your case, when rendering based on some number and not a list, I'd move the for loop outside of the render method for a more readable code:

    renderFields() {
        const noGuest = this.state.guest;
        const fields = [];
        for (let i=0; i < noGuest; i++) {
            // Try avoiding the use of index as a key, it has to be unique!
            fields.push(
                
            );
        }
        return fields;
    }
    
    render () {
        return (
            
                
                    No
                    Name
                    Preference
                
                {this.renderFields()}
            ;
        )
    }
    

    However, there are many more ways to render looped content in react native. Most of the ways are covered in this article, so please check it out if you're interested in more details! The examples in article are from React, but everything applies to React Native as well!

提交回复
热议问题