【Facebook的UI开发框架React入门之九】按钮简介(iOS平台)

(1)设置模式和创建React变量

'use strict';var React = require('react-native');var { AppRegistry, StyleSheet, View, Text, Image, //1.高亮触摸 TouchableHighlight, //2.不透明触摸 TouchableOpacity, //3.无反馈触摸 TouchableWithoutFeedback,} = React;

(2)定义样式

var styles = StyleSheet.create({ container: {//flex: 1,justifyContent: 'center',alignItems: 'center',backgroundColor: 'cyan', }, size: {width: 140,height: 95, }, buttonText: {fontSize: 28,color: 'white',alignSelf: 'center' }, button: {width: 140,height: 95,//flex: 1,//flexDirection: 'row', //子视图排成一行; 默认是排成一列backgroundColor: 'blue',borderColor: 'blue',borderWidth: 1,borderRadius: 8, },});

(3)创建组件对象

var HelloReact = React.createClass({ //定义按钮响应事件处理方法 //1.按键按下 onPressed_btn() {console.log('button pressed !'); }, //2.长按 onLongPress_btn() {console.log('button onLongPress !'); }, //3.被按下时 – 按下按钮不松开,会触发该事件 onPressIn_btn() {console.log('button onPressIn !'); }, //4.松开按钮时 //- 按下按钮后松开,或按下按钮后移动手指到按钮区域外 onPressOut_btn() {console.log('button onPressOut !'); },//1.高亮触摸 TouchableHighlight – 按下时,按钮会有高亮效果//2.透明触摸 TouchableOpacity – 按下时,按钮会半透明并能看到背景//3.无反馈触摸 TouchableWithoutFeedback – 按下时,按钮没有变化,但绑定的响应方法会被系统调用//渲染方法render : function() {return (<View style={styles.container}><TouchableHighlight style = {styles.button} onPress={this.onPressed_btn}><Imagesource={require('image!goodmao')}style={styles.size}/></TouchableHighlight><TouchableOpacity style = {styles.button} onPress={this.onPressed_btn}><Imagesource={require('image!goodmao')}style={styles.size}/></TouchableOpacity><TouchableWithoutFeedback style = {styles.button} onPress={this.onPressed_btn}><Imagesource={require('image!goodmao')}style={styles.size}/></TouchableWithoutFeedback></View>);}});

说明:

1.定义了四个方法,用于处理按钮事件

方法名字,自己定义,注意可读性。

a.按键按下 onPressed_btn( )

b.长按 onLongPress_btn( )

c.被按下时 onPressIn_btn( )

d.松开按钮时 onPressOut_btn( )

2.关联按钮事件与事件处理方法

在按钮的属性中,指定按钮事件和对应的方法即可。

<TouchableHighlightstyle = {styles.button}onPress = {this.onPressed_btn}onLongPress = {this.onLongPress_btn}onPressIn = {this.onPressIn_btn}onPressOut = {this.onPressOut_btn}><Text style={styles.buttonText}>我是按钮</Text></TouchableHighlight>

(4)注册组件

AppRegistry.registerComponent('HelloReact', ()=>HelloReact);

(5)运行效果图

1.三种按钮

2.高亮按钮被按下

3.透明按钮被按下

4.无反馈按钮被按下

三、注意事项

(1)必须给按钮设置子视图

也就是说,按钮必须设置显示的文字或图片,,否则会报错。

例如:

<TouchableHighlight style={styles.button} onPress={this.onPressed_btn}>

<Textstyle={styles.buttonText}>我是按钮</Text>

</TouchableHighlight>

编译运行时,Xcode错误如下:

message: Invariant Violation: onlyChild must be passed a children with exactly one child."

(2)设置文字按钮两种方法

躲在墙角、掩藏那孤独而又不奢怜悯的伤…

【Facebook的UI开发框架React入门之九】按钮简介(iOS平台)

相关文章:

你感兴趣的文章:

标签云: