react native自定义组件以及引用

1、 首页需要新建一个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 (
            
                {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组件,组件的好处是只需要负责内容渲染,不做任何事件处理。


你可能感兴趣的:(react native自定义组件以及引用)