react nativeカスタムコンポーネントおよび参照

5516 ワード

1、トップページにA.jsという名前のAファイルを新規作成する必要がある
そしてファイルに以下の内容を書き込む
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 (
            
                {this.state.title}
                
                 
                /* this.changeCount           ,
                   changeCount={this.changeCount()}       ,
                           ,                
                */
            
        )
    }
}


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

2、次に別のフォルダを作成して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>
    )
}

3、最後の効果
リストがレンダリングされているのが見え、クリックして数値countを変更しても変更が送信され、送信された値が実行されることを説明します.
他の場所でもB/Cコンポーネントを参照できますが、コンポーネントの利点は、コンテンツのレンダリングを担当するだけで、イベント処理をしないことです.