React Native自定义组件、props

原文链接: https://juejin.im/post/5a31d07d51882503eb4b4956

开头导入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 (
			
				
				网易
				新闻
				有态度
				
			
		);
    }
}

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接收外部属性

{this.props.title}
复制代码

其他地方代码一致。注意 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 = (
        		
					  {this.props.news[i]}
				
			);
        	news.push(text);
		}
		return (
			
				进入要闻
				{news}
			
		);
    }
    show(title){
        Alert.alert(title);
    }
复制代码

你可能感兴趣的:(React Native自定义组件、props)