ReactNative实现按钮(简单)

react native实现按钮有4种方式,官方提供的原生TouchableOpacity,TouchableHighlight,TouchableWithoutFeedback,以及第三方封装的按钮

其中原生TouchableOpacity最为常用,TouchableHighlight自带的点击变色效果不够友好,TouchableWithoutFeedback官方不推荐使用。

注意:TouchableOpacity、TouchableHighlight只能有一个子控件,如果有多个要用View包起来。

这里主要讲解TouchableOpacity的实现方法

废话少说先上代码:

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

export default class FirstApp extends Component {
  constructor(props) {
    super(props);
    this.state = {code:1,msg:"测试"};
  }
  showAlert=()=>{
    //使用箭头函数才能用this
    alert(JSON.stringify(this.state));
  }
  render() {
    return (
      <View style={styles.container}>
        <TouchableOpacity style={styles.button}  onPress={this.showAlert}>
            <Text style={styles.buttonText}>按钮</Text>
        </TouchableOpacity>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  button:{
    width:100,
    height:40,
    borderRadius:10,
    backgroundColor:"green", 
    justifyContent:'center',   
  },
  buttonText:{  
    textAlign:"center",
    color:"white"
  }
});

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

解释:

  1. 第13行showAlert() 是点击按钮执行的方法,此处要用函数表达式,或者箭头函数,不要用声明函数的方法,否则在方法里面不能调用this

  2. 第20行 onPress={this.showAlert},是绑定按钮点击事件,注意showAlert后面不要带括号,如果写成 onPress={this.showAlert()}启动后自动调用该方法

  3. 40行justifyContent:’center’表示垂直居中

感谢:
http://reactnative.cn/docs/0.48/tutorial.html#content

http://v.youku.com/v_show/id_XMTUwMTQ4MDA1Mg==.html?spm=a2h0j.8191423.playlist_content.5!3~5~5~A&&f=26822355&from=y1.2-3.4.3

http://blog.csdn.net/bboyklc/article/details/50827969


原文出处:/show_1C77ujvdBQH.html