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 (
      <Text 
      style={{
      color:'blue',
      fontWeight: 'bold',
      fontSize: 30}}>
      
      Hello {this.props.name}!
      
      </Text>
    );
  }
}
//主类
class Bananas extends Component {
  render() 
  
  {//这个是图片地址,一个let变量
    let pic = {uri: 'https://upload.wikimedia.org/wikipedia/commons/d/de/Bananavarieties.jpg'};
  
    return (
    //View视图,设置css属性
      <View style = {{backgroundColor:'green',alignItems:'center'}}>
      //引用Text属性
      <TestText name = '绿香蕉'/>
      <TestText name = '红香蕉'/>
      //图片
      <Image source={pic} style={{width: 200, height: 150 }} />
      <TestText name = '小香蕉'/>
      <TestText name = '大香蕉'/>
      
      </View>
    ); 
  }
}
//注册组件
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(
      <Text style = {{ fontSize:20,color:'red'}}>{display}</Text>
      );
  }

}

//Main
class MarqueeAPP extends Component{
  render(){
    return(
      <View style = {{flex: 1,backgroundColor:'#00ffff', alignItems :'center'}}>
        <Marquee text = 'Hello World !'/>
        <Marquee text = '   '/>
        <Marquee text = 'I love to blink'/>
        <Marquee text = '   '/>
        <Marquee text = 'Yes blinking is so great'/>
        <Marquee text = '   '/>
        <Marquee text = 'Why did they ever take this out of HTML'/>
        <Marquee text = '   '/>
        <Marquee text = 'Look at me look at me look at me'/>
        
      </View>
    );
  }
}
AppRegistry.registerComponent('MyProject',()=>MarqueeAPP);

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容