背景
常用的組件有很多耙旦,今天學(xué)基礎(chǔ)組件以及他們的常用設(shè)置朋蔫。我覺得還是看代碼能直觀一點,也順便熟悉一下語法捏膨。
導(dǎo)包
從react-native中導(dǎo)入需要的組件秧均,{}種的內(nèi)容就是要導(dǎo)入的組件。
import React, { Component } from 'react';
import { AppRegistry, Image ,Text,View} from 'react-native';
組件
從上面的代碼中可以看出一共導(dǎo)入了以下4個組件:
組件 | 說明 |
---|---|
AppRegistry | 注冊(必須導(dǎo)入) |
Image | 圖片 |
Text | 文字 |
View | 綜合視圖 |
樣式
和js一樣的原則脊奋,仍然是用css定義熬北,只是命名上采用 駝峰命名法。
顏色
- 默認(rèn)使用color
- 其他采用駝峰诚隙,如backgroundColor
- 支持十六進制讶隐,如 #000000效果和black一樣
示例
//導(dǎo)入
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視圖,設(shè)置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)寫好了之后是無法改變的久又,所以需要涉及到了狀態(tài)(state)巫延,個人理解,這個state應(yīng)該和監(jiān)聽器差不多吧地消。
- props定義了屬性
- state改變狀態(tài)
綜合效果
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(){
//根據(jù)當(dāng)前showText的狀態(tài)判斷是否顯示text內(nèi)容
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);