如何自定义一个NavigationBar

    xiaoxiao2022-06-25  239

    一个NavigationBar包含有导航栏和状态栏两个部分。

     

    如何自定义React Native组件?

    1. 首先需要继承React.Component

    export default class NavigationBar extends Component{ }

    2. 实现render方法

    render(){ return ( <View> ...... </View> ) }

    3. 对属性进行类型检查

           自定义组件往往会提供一些属性供外界调用,进行属性检查是为了确保使用该自定义组件的时候能够正确设置属性

          React中内置了类型检查的功能,要检查组件的属性,你需要配置特殊的propTypes属性:

    import PropTypes from 'prop-types'; class NavigationBar extends React.Component { //设置所提供属性的类型检查 static propTypes = { title: PropTypes.string, } render(){ return ( <Text>{this.props.title}</Text> ); } //或者也可以用这种方式进行属性检查 NavigationBar.propTypes = { title: PropTypes.string, }

    4. 设置默认属性

           有时我们需要为自定义组件设置默认属性以满足不同的业务需求,但在使用这个组件时并不是所有的属性都要设置,所以对于有些属性我们需要设置默认值,

          React 提供了defaultProps来为一个组件设置默认属性,这对于未定义的(undefined)的属性来说有用,而对于设为空(null)的属性并没有用。

    class NavigationBar extends React.Component{ //设置默认属性 static defaultProps = { title: 'Test' }; } //或者 NavigationBar.defaultProps = { title: 'Test' }

    5. 使用自定义组件

    import NavigationBar from './NavigationBar'; .... <NavigationBar title={'最热'} /> .....

    相关高度参数设置

    通常来讲导航栏的高度在IOS和Android中不同的,可以根据需要分别进行设置

    const NAV_BAR_HEIGHT_IOS = 44;//导航栏在IOS中的高度 const NAV_BAR_HEIGHT_ANDROID = 50;//导航栏在Android中的高度 const STATUS_BAR_HEIGHT = 20;//状态栏的高度

    状态栏StatusBar

    React Native提供了StatusBar组件以方便我们来设置状态栏

    设置属性类型检查

    下面是我们对NavigationBar 的属性检查的设置,这里的PropTypes需要使用prop-types,使用prop-types需要首先将它安装到项目中;

    yarn add prop-types

    import {ViewPropTypes} from 'react-native'; import {PropTypes} from 'prop-types'; const StatusBarShape = {//设置状态栏所接受的属性 barStyle: PropTypes.oneOf(['light-content','default']), hidden: PropTypes.bool, backgroundColor: PropTypes.string, }; static propTypes = { style:ViewPropTypes.style, title:PropTypes.string, titleView: PropTypes.element, titleLayoutStyle:ViewPropTypes.style, hide: PropTypes.bool, statusBar: PropTypes.shape(StatusBarShape), rightButton; PropTypes.element, leftButton: PropTypes.element, } ;

    设置默认属性

    有些属性是非必须设置的,比如statusBar,这些非必须设置的参数我们需要为它定义默认属性。

    static defaultProps = { statusBar: { barStyle: 'light-content',//多个页面设置,只第一个页面设置有效 hidden: false, }, };

    实现render方法

    接下来进行最重要的一步,实现render方法:

    render() { let statusBar = !this.props.statusBar.hidden ? <View style={styles.statusBar}> <StatusBar {...this.props.statusBar}/> </View> : null; let titleView = this.propstitleView ? this.props.titleView : <Text ellipsizeMode='head' numberOfLines={1} style={styles.title}>{this.props.title}</Text>; let content = this.props.hide ? null : <View style={styles.navBar}> {this.getButtonElement(this.props.leftButton)} <View style={[styles.navBarTitleContainer.this.props.titleLayoutStyle]}> {titleView} </View> {this.getButtonElement(this.props.rightButton)} </View> return ( <View style={[styles.container,this.props.style]}> {statusBar} {content} </View> ) }

     


    最新回复(0)