react-native 自定义容器组件-this.props.children
日期: 2019-06-02 分类: 个人收藏 362次阅读
自定义容器组件是什么样子的呢??首先看一个效果(上面的toolbar):
代码上的使用是这样的,自定义容器组件集成了组件<SafeAreaView/> <StatusBar/> <SimpleHeaderbar/>
三个组件来实现和适配 iOS和Android平台下的头部显示。
自定义之后,看使用方式
容器组件 定义的核心就是this.props.children
。
但是在使用this.props.children
的时候有几个点需要注意;
this.props.children
在View中使用的时候,一般的系统默认会把ta当作子View。但是如果使用方式不当,则会被当作Object,而无法实现作为子View来实现容器组件。
接下来分析一下我的代码,
/**
* @Author: yuanjunhua
* @Company: 悦旅大人
* @Date: 2019-5-31 15:09
* @Description: 自定义 toolbar —— 包含:安全区+状态栏+顶部导航
*
*/
import { PropTypes } from "prop-types";
import React, { Component } from "react";
import {
requireNativeComponent,
View,
PixelRatio,
Platform,
StatusBar,
SafeAreaView,
StyleSheet
} from "react-native";
import {
screenW,
screenH,
scaleSizeW,
scaleSizeH,
StatusBarHeight,
__IOS__,
setSpText,
isIphoneX
} from "../util/NavigationService";
import SimpleHeaderbar from "./SimpleHeaderbar";
import DrawableIndex from "../res/DrawableIndex";
class SafeAreaStatusBarHeaderbar extends Component {
static defaultProps = {
StyleSheet: {
backgroundColor: "#FFFFFF", //页面颜色
backIcon: DrawableIndex.public.ic_back_black, //返回按钮的图标
middleTitle: "", //toolbar中间字体内容
bgColor: "#FFFFFF", //toolbar颜色
middleTitleColor: "#000000", //中间字体颜色=右边字体颜色
rightTxt: null, //右边字体内容
moreIcon: null //右边字体图标
},
barTxtColor: "dark-content", //状态栏字体颜色
statusBarHidden: false
};
static propTypes = {
children: PropTypes.element,
StyleSheet: PropTypes.object.required,
onClick: PropTypes.func
};
render() {
let {
backgroundColor,
backIcon,
middleTitle,
bgColor,
middleTitleColor,
rightTxt,
moreIcon,
barTxtColor
} = this.props.StyleSheet;
return (
<SafeAreaView
{...this.props}
style={[styles.container, { backgroundColor }]}
forceInset={{ top: "never", bottom: __IOS__ ? "never" : "always" }}
>
{/*状态栏*/}
<StatusBar
animated={true} //指定状态栏的变化是否应以动画形式呈现。目前支持这几种样式:backgroundColor, barStyle和hidden
hidden={this.props.statusBarHidden} //是否隐藏状态栏。
backgroundColor={"transparent"} //状态栏的背景色
translucent={true} //指定状态栏是否透明。设置为true时,应用会在状态栏之下绘制(即所谓“沉浸式”——被状态栏遮住一部分)。常和带有半透明背景色的状态栏搭配使用。
barStyle={this.props.barTxtColor}
/>
<SimpleHeaderbar
onClick={this.props.onClick}
rightTxt={rightTxt}
moreIcon={moreIcon}
backIcon={backIcon}
navigation={this.props.navigation}
middleTitle={middleTitle}
bgColor={bgColor}
middleTitleStyle={{ color: middleTitleColor }}
/>
{this.props.children}
</SafeAreaView>
);
}
}
export default SafeAreaStatusBarHeaderbar;
const styles = StyleSheet.create({
container: {
flex: 1
}
});
看代码第88行 this.props.children
直接放在了容器组件 <SafeAreaView/>
中。如果在 this.props.children
的外层包裹一层<View></View>
则会出现异常。因为ta被当作了字符串内容,提示需要放进<Text></Text>
中。然后我的推测是,要排除 this.props.children
被当作别的内容(属性、方法等)。就需要在 this.props.children
的父类容器中除去 this.props.children
以外,还要有View填充。这样一个自定义组件容器就实现了。
除特别声明,本站所有文章均为原创,如需转载请以超级链接形式注明出处:SmartCat's Blog
精华推荐