React-native第一课,Button的添加

    前两天开始着手react-native,之前的时间都费在环境上了,今天正式代码的第一课。看过网上的资料,现在综合整理一下以备后续查看。

    首先,react-native 的环境配置见http://reactnative.cn/docs/0.24/getting-started.html#content

    然后进入代码环节了,我这里编写代码的环境是Atom。


    首先是在页面中显示一个Button,图片如下。



   实现代码如下,修改index.android文件,我这里用到的按钮控件为 TouchableOpacity

 import React, {
  AppRegistry,
  Component,
  StyleSheet,
  Text,
  View,
  TouchableOpacity   <--加入引用
} from 'react-native';


  render() {
    return (
     
            加入控件,这里的属性设置为使用的style,以下会有代码
       
          确定         <--------显示字体
       

       

     

    );
  }


const styles = StyleSheet.create({          <-------style定义
  button:{
    height: 80,
    width: 200,
    backgroundColor:'gray',
   justifyContent:'center',
   borderRadius: 20,
    },
 textstyle:{
   textAlign:'center',
   fontSize:20,
 },......


      这样单纯的显示Button就完成了,其次关心的一定是Button的点击事件了,那么以下我们就来实现以下Button的点击事件吧

      给 TouchableOpacity添加点击事件的属性是onPress,有点像android中在xml给button添加点击事件的方法。

    class Test extends Component {
    οnclick=() => {
       alert('我点击了按钮');
    };


  render() {
    return (
     
                 style={styles.button}
         onPress ={this.onclick}
         >
       
          确定
       



       
     

    );
  }
}

   这样的话简单的点击事件就处理完了。我们下面尝试自己封装一个Button,主要牵扯到一些JS的用法,对于像我这种java选手刚接触到JS的来说,下面的代码还是蛮精致的。

   首先沾代码的。自己的Button

  /**
 * xiaoaxue 2016.4.21
 */

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

export default class Button extends Component {

constructor(props){
    super(props);
    this.state = {
      _text:props.text,
    }
  }
  οnclick=() => {
      alert('我点击了按钮');
  };

  render() {
    //大括号叫解构,将props中的属性text取出来放入text中,好处是可以取多个值
    const {text,background}  = this.props;
    return (
     
                style={[styles.button,{backgroundColor:background}]}>
       
         {/*{this.props.text}*/}
        {this.state._text}
       

       
     

    );
  }
}


const styles = StyleSheet.create({
  button:{
    height: 80,
    width: 200,
    backgroundColor:'gray',
   justifyContent:'center',
   borderRadius: 20,
 },
 textstyle:{
   textAlign:'center',
   fontSize:20,
 },
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
});

  

index中修改:

import Button from './src/component/Button';


class Test extends Component {
  render() {
    return (
     
      {/* props,属性*/}
       

你可能感兴趣的:(react-native)