react-native 自定义容器组件-this.props.children

自定义容器组件是什么样子的呢??首先看一个效果(上面的toolbar):
react-native 自定义容器组件-this.props.children_第1张图片
代码上的使用是这样的,自定义容器组件集成了组件 三个组件来实现和适配 iOS和Android平台下的头部显示。
react-native 自定义容器组件-this.props.children_第2张图片
自定义之后,看使用方式
react-native 自定义容器组件-this.props.children_第3张图片
容器组件 定义的核心就是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 (
      
        {/*状态栏*/}
        
    );
  }
}

export default SafeAreaStatusBarHeaderbar;

const styles = StyleSheet.create({
  container: {
    flex: 1
  }
});

看代码第88行 this.props.children 直接放在了容器组件 中。如果在 this.props.children 的外层包裹一层则会出现异常。因为ta被当作了字符串内容,提示需要放进中。然后我的推测是,要排除 this.props.children 被当作别的内容(属性、方法等)。就需要在 this.props.children 的父类容器中除去 this.props.children 以外,还要有View填充。这样一个自定义组件容器就实现了。

你可能感兴趣的:(react-native)