鱼C论坛

 找回密码
 立即注册
查看: 2635|回复: 0

[技术交流] RN教程之按钮与state关键字

[复制链接]
发表于 2017-8-7 10:36:10 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
  1. import React, { Component } from 'react';
  2. import {
  3.   AppRegistry,
  4.   View,
  5.   Text,
  6.   TouchableHighlight
  7. } from 'react-native';

  8. export default class myreact extends Component {
  9.   constructor(props) {
  10.     super(props);
  11.   
  12.     this.state = {action:false};
  13.   }
  14.   render() {
  15.     return (
  16.             <View style={{flex:1}}>
  17.       <TouchableHighlight
  18.       onPress={()=>this.setState({action:!this.state.action})}
  19.       style={{backgroundColor: 'gray',width: 150,height: 90}}
  20.       >
  21.       <Text>press me</Text>
  22.       </TouchableHighlight>
  23.       {
  24.         this.state.action?<Text style={{fontSize: 50,marginTop: 100}}>hello</Text>:null
  25.       }
  26.       </View>
  27.     );
  28.   }
  29.   
  30. }

  31. AppRegistry.registerComponent('myreact', () => myreact);
复制代码

TouchableHighlight 控件:点击后背景色变暗

onPress 属性:设置一个箭头函数来调用点击事件

this.state属性:在构造函数里先初始化

this.setState 函数:改变state属性的值

这里state必须是一个json类型,TouchableHighlight标签里不止能放Text控件,还可以放任何其他控件。以上代码我设置了个state属性,然后在onPress事件里给它取反,再在底下放了一个三元操作符的变量,就是如果this.state.action是真就显示hello,如果是假就显示空,显示效果为下图:
jdfw.gif

本帖被以下淘专辑推荐:

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-4-19 12:55

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表