React Native学习笔记4:基础组件

背景

常用的组件有很多,今天学基础组件以及他们的常用设置。我觉得还是看代码能直观一点,也顺便熟悉一下语法。

导包

从react-native中导入需要的组件,{}种的内容就是要导入的组件。

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

组件

从上面的代码中可以看出一共导入了以下4个组件:

组件 说明
AppRegistry 注册(必须导入)
Image 图片
Text 文字
View 综合视图

样式

和js一样的原则,仍然是用css定义,只是命名上采用 驼峰命名法

颜色

  • 默认使用color
  • 其他采用驼峰,如backgroundColor
  • 支持十六进制,如 #000000效果和black一样

示例

//导入
import React, { Component } from 'react';
import { AppRegistry, Image ,Text,View} from 'react-native';
//自定义Text
class TestText extends Component {
  render() {
    return (
      
      
      Hello {this.props.name}!
      
      
    );
  }
}
//主类
class Bananas extends Component {
  render() 
  
  {//这个是图片地址,一个let变量
    let pic = {uri: 'https://upload.wikimedia.org/wikipedia/commons/d/de/Bananavarieties.jpg'};
  
    return (
    //View视图,设置css属性
      
      //引用Text属性
      
      
      //图片
      
      
      
      
      
    ); 
  }
}
//注册组件
AppRegistry.registerComponent('MyProject', () => Bananas);

props和state

上面的一段代码(props)写好了之后是无法改变的,所以需要涉及到了状态(state),个人理解,这个state应该和监听器差不多吧。

  • props定义了属性
  • state改变状态

综合效果


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

class Marquee extends Component{
  constructor(props){
    super(props);
    this.state = {showText: true};
    //每秒钟对showText做一次取反
    setInterval(()=>{
      this.setState({
        showText: !this.state.showText 
      });
    },2000);
  }

  render(){
    //根据当前showText的状态判断是否显示text内容
    let display = this.state.showText ? this.props.text :'';
    return(
      {display}
      );
  }

}

//Main
class MarqueeAPP extends Component{
  render(){
    return(
      
        
        
        
        
        
        
        
        
        
        
      
    );
  }
}
AppRegistry.registerComponent('MyProject',()=>MarqueeAPP);

 

                            
                        
                    
                    
                    

你可能感兴趣的:(React Native学习笔记4:基础组件)