React native自定义组件之Button按钮

最近也是在自学react native这一块,其中也踩了不少坑,由于使用windows环境,可能是因为运气不好,最开始配环境的时候就出现了很多问题,当成功之后也发现,啊哈,原来如此,有一朋友就很顺利一遍就成功。好了还是进入主题,在Android原生开发中我们大多都会事先在drawable中定制几个按钮然后在项目中直接调用很方便。当然,在react native开发中我们也可以事先写好一个button,然后在import进来直接使用。接下来我把主要步骤记录下来,方便以后查看,也可以给初学者做做参考,谢谢。
1,第一步先在项目中新建button.js文件,button中的代码如下:

import React, { Component } from 'react';

import {
  View,
  Text,
  Dimensions
} from 'react-native';

import { flextCenter } from './values/style'

export default class Button extends Component {
  render(){
    return(
      <View style = {{...flextCenter,backgroundColor:'blue',width:Dimensions.get('window').width-40,height:45}}>
        <Text style = {{color:'white',fontSize:20}}>登录</Text>
      </View>
    );

其中 class Button 组件一定要导出去也就是使用export default 关键字,这样外面才可以引用,至于代码中的…flextCenter的使用是这么来的,我事先建了style.js文件,然后文件中声明了flextCenter变量代码如下:

export const flextCenter={justifyContent:'center',alignItems:'center'}

其中也使用了export class关键字,这样在button.js文件中导入flextCenter就可以直接使用了,导入代码如下

import { flextCenter } from './values/style'

由于flextCenter是一个变量所以用了{},这样在组件中就直接可以使用该属性了,至于这两个属性的作用我就不多提了。当然,如果使用的属性更多,你还可以在该变量中加入其他属性比如backgroundColor都是可以的。

然后就是在其他组件中使用Button组件了,这里我新建了find.js文件,文件中的代码如下:

import React,{Component} from 'react';

import {
  View,
  StyleSheet
} from 'react-native';

import Button from './button'



export default class Find extends Component{

  render(){
    return(
      <View style = {styles.container}>
        <Button/>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container:{
    flex:1,
    justifyContent:'center',
    alignItems:'center',
  },
})

为了方便我是在index.android.js中注册的Find,代码如下:

import React, { Component } from 'react';
import {
  AppRegistry,
} from 'react-native';

import Find from './app/find'




AppRegistry.registerComponent('MyScreen', () => Find);

最后实现的效果图如下:

其实我们在原生开发中大多按钮都是带有圆角的,我们只需要在组件Button中给View多增加一些样式就可以实现,增加代码如下

borderRadius:20

然后效果图:

至此其实自定义组件Button已经可以使用了,其实还有很多不足,比如,宽度高度都是我们事先写死了,也就是固定的,这样使用起来也很不方便,接下来我们修改button.js中的代码,然后可以让使用者自定义宽高以及背景颜色还有文字:

  render(){
    const {width,height,backgroundColor,children,borderRadius} = this.props
    return(
      <View style = {{...flextCenter,backgroundColor,width,height,borderRadius}}>
        <Text style = {{color:'white',fontSize:20}}>{children}</Text>
      </View>
    );
  }

引用组件部分代码:

render(){
    return(
      <View style = {styles.container}>
        <Button backgroundColor = {'blue'}
        width = {Dimensions.get('window').width - 40}
        height = { 45 }
        borderRadius = { 20 }>
        这是自定义组件
        </Button>
      </View>
    );
  }

效果图:

现在该组件稍加修改已经可以满足大部分需求了,由于我也是学习这块没多久不足之处还请多多见谅。

最后我自己也在用React native 写了一个小项目,也是抽时间再写,完成了登录注册模块,然后导航栏也加进去了,我会抽时间把这个项目逐渐完善,最后也是附上项目地址,希望大家多多指教。谢谢。

项目地址

猜你喜欢

转载自blog.csdn.net/zhuhuitao_struggle/article/details/75331775