React Native - 给组件属性指定默认值
作者:hangge | 2017-08-24 08:10
1,指定属性默认值
(1)我们可以在自定义组件中设定属性默认值,这样当组件被渲染时,如果没有指定某个属性的值,则使用默认值。
(2)与前文的属性确认声明类似(点击查看),通过在自定义组件定义结束后增加语句来为属性指定默认值。语法如下:
组件.defaultProps = {
属性1: value1,
属性2: value2,
}
2,样例演示
(1)下面是一个自定义的列表组件(list.js),通过属性 news 获取列表内容并显示。这里我们给其设置个默认值。
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View,
} from 'react-native';
export default class List extends Component {
show(title) {
alert(title);
}
render() {
var news = [];
for(var i in this.props.news){
var text = (
<View key={i} style={styles.list_item}>
<Text
onPress={this.show.bind(this, this.props.news[i])}
numberOfLines={1}
style={styles.list_item_font}>
{this.props.news[i]}
</Text>
</View>
);
news.push(text);
}
return (
<View style={styles.flex}>
{news}
</View>
);
}
}
//添加属性确认
List.defaultProps = {
news: [
'Swift - 滑块(UISlider)的用法',
'Swift - 告警框(UIAlertView)的用法',
'Swift - 选择框(UIPickerView)的用法'
],
}
const styles = StyleSheet.create({
flex:{
flex:1
},
list_item:{
height:40,
marginLeft:10,
marginRight:10,
borderBottomWidth:1,
borderBottomColor: '#ddd',
justifyContent: 'center'
},
list_item_font:{
fontSize:16
},
});
(2)下面使用这个组件,注意我们没有传递任何值给 List 组件。
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
View,
} from 'react-native';
//导入自定义的列表组件
import List from './list'
class Main extends Component {
render() {
return (
<View style={styles.flex}>
<List></List>
</View>
);
}
}
const styles = StyleSheet.create({
flex:{
flex:1
},
});
AppRegistry.registerComponent('HelloWorld', () => Main);
(3)由于使用时没有设置 List 组件的 news 属性值,则自动使用默认值,运行结果如下:

全部评论(0)