React Native中Touchable组件的使用

截图如下:

/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  View,
  TouchableOpacity,
  AlertIOS,
} from 'react-native';


// ES5写法
 var ViewDemo = React.createClass({

   getInitialState(){

     return{
       title: '不透明触摸'
     }
   },
   render() {
     return (

         <View style={styles.container} onPress = {this.rendPress()}>

     <TouchableOpacity activeOpacity = {0.2}
      onPress = {()=>this.activeEvent('点击了啦!!!')}
      onPressin = {()=>this.activeEvent('按下了啦!!!')}
      onPressout = {()=>this.activeEvent('抬起了啦!!!')}
      onLongPress = {()=>this.activeEvent('长按了啦!!!')}
      >
         <View style = {styles.innerStyle}>
              <Text>点击事件</Text>
          </View>
     </TouchableOpacity>
     <View>
          <Text>{this.state.title}</Text>
     </View>
     </View>
   );
   },  // ,号在ES5必须写,ES6可以不写

   // 当按下鼠标
   rendPress(){
     AlertIOS.alert('点击了')
   },
   activeEvent(event){
     this.setState({
       title: event
     })
   }
});


// ES6写法

/*
class ViewDemo extends Component {

  render() {
    return (

      <View style={styles.container} onPress = {this.rendPress()}>

         <TouchableOpacity activeOpacity = {0.2}>
         <View style = {styles.innerStyle}>
             <Text>我是文本,但是可以点击!!!</Text>
         </View>
         </TouchableOpacity>
     </View>
    );
  }

  // 当按下鼠标
  rendPress(){
    AlertIOS.alert('点击了')
  }
}
*/

const styles = StyleSheet.create({
  container: {

    backgroundColor: 'green',  // 设置背景颜色
     400,  // 宽度
    height: 300  // 高度 最后一个样式的,可以不写,其余的必须写,不然报错
  },
  innerStyle: {
    backgroundColor: 'red',
     300,
    height: 80,
    marginTop: 100,
  },
  innerStyle1: {
    backgroundColor: 'yellow',
     100
  },
});

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

代码如下:

原文地址:https://www.cnblogs.com/pengsi/p/5903648.html