React Native入门(三)之Props(属性)和State(状态)
前言这篇文章来介绍一下RN的属性和状态,以及在之前Hello World项目中已经出现的比如style等UI样式的使用,之后我们就能使用这些来搭建一些简单的UI界面。 还记得搭建环境的时候init的AwesomeProject项目吧,我们把它导入到WebStorm中,下边的内容都可以在里边改代码! Props(属性)大多数组件在创建时就可以使用各种参数来进行定制。用于定制的这些参数就称为props(属性)。 我们还是来对比Android中的属性,比如TextView,常见的 这里我们举个例子,以RN中的 import {
AppRegistry,Image,StyleSheet,Text,View
} from 'react-native';
我们在项目中将Image添加进来,之后就可以使用这个组件了! let pic={ uri: 'http://p4.music.126.net/cq1STvQ6q5b_Eg5grsTjYQ==/3275445147663993.jpg' }; //加载网络图片,必须指定图片尺寸 return ( <View style={styles.container}> <Image source={pic} style={{width: 200,height: 200}} /> <Text style={styles.welcome}>This is a picture of Taylor Swift</Text> </View> );
然后我们运行一下,看一下效果! 代码中 需要注意的一点: 跟我们直接把地址放进去是一样的: <Image source={{uri: 'http://p4.music.126.net/cq1STvQ6q5b_Eg5grsTjYQ==/3275445147663993.jpg'}} style={{width: 200,height: 200}} />
另外就是,Image组件在加载网络图片的时候,必须要指定宽高,这个先记着就行,关于图片我们之后再做讨论! 还有就是代码中 样式style这里style也是Image的属性,而且几乎全部的组件都有style这个属性,这里主要用来设置宽高,而且是直接在里边写了 const styles = StyleSheet.create({ container: { flex: 1,justifyContent: 'center',alignItems: 'center',backgroundColor: '#F5FCFF',},welcome: { fontSize: 20,textAlign: 'center',margin: 10,instructions: { textAlign: 'center',color: '#333333',marginBottom: 5,});
在外边声明style,然后再去引用是一样的。 关于style,这些样式名基本上是遵循了web上的CSS的命名,只是按照JS的语法要求使用了驼峰命名法,例如将 <Text style={[styles.container,styles.instructions]}>
重点:后声明的属性会覆盖先声明的同名属性。 自定义组件的属性我们在前一篇博客中说过,可以 class Description extends Component{
render() {
return (
<Text style={styles.welcome}>This is a picture of {this.props.name}</Text>
);
}
}
然后这样用: return ( <View style={styles.container}> <Image source={pic} style={{width: 200,height: 200}} /> <Description name="Taylor Swift"/> </View> );
这里的 重新reload一下,发现运行效果是一样的! State(状态)这里借助官网的说明: 我们使用两种数据来控制一个组件: 通过上面的描述,我们发现思路呢和java代码很类似啊,constructor顾名思义构造器,在构造器中给state初始化一个值,然后如果需要修改,就调用 class Description extends Component {
constructor(props) {
super(props);
this.state = { showText: true };
// 每1000毫秒对showText状态做一次取反操作
setInterval(() => {
this.setState(previousState => {
return { showText: !previousState.showText };
});
},1000);
}
render() {
// 根据当前showText的值决定是否显示text内容
// 这里稍微改动一下
let text="This is a picture of " + this.props.name;
let display = this.state.showText ? text : ' ';
return (
<Text>{display}</Text>
);
}
}
reload一下,就可以看见这些字一闪一闪的了! 结语本篇文章过后,我们就了解了组件的属性和状态,以及为组件设置样式style,包括自定义组件。这样我们能够基本编写出一些简单的UI界面了! 好了,先这样了,下篇再见! (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |