React Native 定义组件 引用组件
框架自带很多的常用组件,但是如果不能满足产品需求,如何自定义呢?
这里悄悄的提醒各位初次接触React Native的并且没有js和es6语法基础的同学,一定要先看看相关资料,否则的话上手很慢,因为写法上的差异会让你摸不着头脑(因为我就是这样的?)。
-
第一步定义一个自己的组件
//第一部分 引入需要的控件, import React, {Component} from 'react'; import{ Button, } from 'react-native'; //继承Component,里面有一个必须要实现的方法render,渲染组件使用,并且只能有一个根view,这里有点类似Android里的ScrollView export default class MyButton extends Component { render() { return ( //this.props.xx 来引用属性 <Button color={this.props.color} title={this.props.title} onPress={this.props.onPress} /> ) } } //注册到module,类似于在系统注册了这个组件 module.exports = MyButton;
-
使用这个定义好的组件
//重点看这里,这是把自己写的组件引入的地方
var MyButton = require('./jscontent/MyButton');
export default class learnRn extends Component {
render() {
return (
<View style={styles.container}>
//直接使用啦,可以设置一些属性
<MyButton
color='#f33444'
onPress={()=> {
Alert.alert('Himi', ' MyBtton IS Click! ');
}}
title="我是一个按钮"
/>
</View>
);
}
总结
上面就是最简单的组件定义和使用了,组件其实也是有生命周期的,会在以后进行实践中介绍。