1. 程式人生 > >react-native 返回元件的問題

react-native 返回元件的問題

問題描述:在react-native中,我們開發一個元件時最終返回的內容一般都是一個 View 或者 Content 元件,其餘的內容都包裹在這個元件中進行返回。直接來說,我們最終只相當於返回的一個 View 或者 Content 元件!!如下圖:

程式碼:

export class Demo extends Component {

    constructor() {
        super();
        this.state = {
            
        };
    }

    render() {
        return (
            <Container>
                <HeaderDark>
                    <Left>
                        <HeaderBack navigation={this.props.navigation}/>
                    </Left>
                    <Body>
                    <HeaderCaption>整改詳情</HeaderCaption>
                    </Body>
                    <Right></Right>
                </HeaderDark>

                <Content contentContainerStyle={{flex: 1,justifyContent: 'flex-start',alignItems: 'stretch',overflow: 'hidden',
                    backgroundColor: '#fff',borderRadius: 8,marginHorizontal:19,marginBottom: 19, padding:16,}}>
                    <Text>內容1</Text>
                    <Text>內容2</Text>
                    <Text>內容3</Text>
                    <Text>內容4</Text>
                    <Text>內容5</Text>
                </Content>
            </Container>
        );
     }

}

效果:

但是:如果需要同時返回幾個 View 或者 Content 時,該怎麼辦呢?

方法1:在幾個 View 的最外面再包裹一個總的 View,如下圖:

方法2:return返回一個數組,陣列元素為 單個的 View 或者 Content元件,如下圖:

        注意:1. 這種方法和 方法1 在原理上其實是一個的,最終都是放回一個 Container 元件。

                   2. 這種方式不能用在 render 中,只能用在函式中返回 元件 的情況。

renderCon 函式:

效果如下(和直接寫在 render 中是一樣的):

文章僅為本人學習過程的一個記錄,僅供參考,如有問題,歡迎指出!