react native自定義組件以及引用

一、 首頁須要新建一個A文件命名爲A.js

而且在文件裏面寫入如下內容



import React, { Component } from 'react';
import {Text,View,StyleSheet} from 'react-native';
import {B,C} from './Components'; // 引入組件
export default class A extends Component {
    constructor(props) {
        super(props);
        this.state = {
            title: '我是首頁',
            data: [1,2,3,4,5,6],
            count: 0
        }
    }
    
    changeCount = (c) => {
        // 獲取傳來的值
        this.setState({
            count: c
        })
    }

    // 頁面
    render() {
        return (
            <View style={styles.container}>
                <Text style={styles.title}>{this.state.title}</Text>
                <B data={this.state.data}/>
                <C count={this.state.count} changeCount={this.changeCount}/> 
                /* this.changeCount在這裏是不須要加括號的,
                   changeCount={this.changeCount()}這個是錯誤寫法,
                   若是好奇爲何錯,能夠嘗試加括號執行一遍看看效果 
                */
            </View>
        )
    }
}


const styles = StyleSheet.create({
    container: {
        flex:1,
        backgroundColor:'#fff',
        alignItems: 'center',
        justifyContent:'center'
    },
    title: {
        fontSize:25
    }
  });複製代碼



二、 其次建立另一個文件夾命名爲Components.js

在裏面寫入以下內容


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

// 這個是B組件,渲染循環列表內容
export const B = ({data}) => {
    return (
        <View> { data.map((item,index) => { return ( <View style={{width:50,justifyContent:'center',alignItems: 'center'}}> <Text>{item}</Text> </View> ) }) } </View>
    )
}

// 這個是C組件 負責渲染count的值,並有點擊事件
export const C = ({count,changeCount}) => {
    return (
        <View> <Text>我是C組建</Text> <Text onPress={() => changeCount(count+1)}>改變數值</Text> <Text>{count}</Text> </View>
    )
}複製代碼



三、最後的效果





能夠看到列表被渲染出來了,點擊改變數值count也發送了改變,說明傳來的值被執行。

其餘地方一樣能夠引用B/C組件,組件的好處是隻須要負責內容渲染,不作任何事件處理。

相關文章
相關標籤/搜索