React Native自定义组件、props

开头导入React

import React, { Component } from 'react';
复制代码

导入需要的组件

import {
    AppRegistry,
    StyleSheet,
    View,
    Text
} from 'react-native';
复制代码

最后一行必须加

module.exports =  Header; //后面放类名
复制代码

例子:

import React, { Component } from 'react';
import {
    AppRegistry,
    StyleSheet,
    View,
    Text,
	PixelRatio
} from 'react-native';
class Header extends Component{
	render(){
		return (
			<View style={styles.flex}>
				<Text style={styles.font}>
				<Text style={styles.font1}>网易</Text>
				<Text style={styles.font2}>新闻</Text>
				<Text>有态度</Text>
				</Text>
			</View>
		);
    }
}

const styles = StyleSheet.create({
		flex:{
			marginTop:25,
			height:50,
			borderBottomWidth: 3/PixelRatio.get(),
			borderBottomColor: '#EF2D36',
			alignItems: 'center',
		},
		font:{
			fontSize: 25,
			fontWeight: 'bold',
			textAlign: 'center',
		},
    	font1:{
     	   color: '#CD1D1C',
   		 },
   		 font2:{
             color: '#FFF',
			 backgroundColor: '#CD1D1C',
   		 },

});

module.exports =  Header;
复制代码

需要的文件中 首字母必须大写 否则会报错

var Header = require('./js/components/Header.js');
复制代码

props

在自定义组件我们希望可以把标题传入到组件中,而不是写死。 在这通过props接收外部属性

<Text style={styles.list_item_font}>{this.props.title}</Text>
复制代码

其他地方代码一致。注意 module.exports = ImportantNews; 后面为类名 新建一个数组。 将参数中的news变为text数组传入。
.push()相当于 .add numberOfLines为两行 onPress调用text的点击事件。传递参数时需要.bind这个参数第一个参数为上下文对象,this,第二个为传递数据,这里传入传入的文本, 之后使用的 alert函数。为全局函数 在View下直接使用{news}


	render(){
        var news = [];
        for(var i in this.props.news){
        	var text = (
        		<Text onPress={this.show.bind(this,this.props.news[i])}
					  numberOfLines={2}
					  style={styles.news_item}>
					  {this.props.news[i]}
				</Text>
			);
        	news.push(text);
		}
		return (
			<View style={styles.flex}>
				<Text style={styles.news_title}>进入要闻</Text>
				{news}
			</View>
		);
    }
    show(title){
        Alert.alert(title);
    }
复制代码
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值