Implementation of React Native Custom Title Bar Component

  • 2021-07-13 04:28:00
  • OfStack

Hello, everyone, today, let's talk about how to implement a custom title bar component. We all know that RN has one advantage, that is, it can be componentized. It is enough to directly reference and pass some parameters where the component needs to be used. This way really improves the development efficiency.

The title bar is an essential part of most application interfaces, so it is necessary to peel off the title bar and make it into a component. Today, let's talk about a title bar without a return button. Cut the crap and go directly to the code:


/** 
 *  Encapsulates a common header without a return button  
 */ 
'use strict'; 
import React, { Component } from 'react'; 
import { 
 Text, 
 View, 
} 
from 'react-native'; 
import StyleSheet from 'StyleSheet'; 
export default class HeaderNoBack extends Component { 
 render() { 
  return ( 
    <View style={styles.container}> 
     <View style={styles.textview}> 
      <Text style={styles.textstyle}>{this.props.text || " Header "}</Text> 
     </View> 
    </View> 
  ); 
 } 
} 
const styles = StyleSheet.create({ 
 container: { 
  flexDirection: 'row', 
  alignItems: 'center', 
  height: 45, 
  alignSelf: 'stretch', 
  backgroundColor: '#4a9df8', 
 }, 
 textview: { 
  flex: 1, 
  alignSelf: 'center', 
 }, 
 textstyle: { 
  fontSize: 18, 
  color: '#fff', 
  textAlign: 'center', 
 }, 
}); 

The code is relatively simple, so we have done too much analysis here, but we should emphasize one point. this. props. text shows the text to be displayed when it is passed in. If there is no text attribute passed in, the default display is "title header".

Example of how to use:


import HeaderNoBack from '../../../component/Header/HeaderNoBack'; 
<HeaderNoBack text=' I am the title '/> 

The above code mainly uses View and Text components, and the style uses flex layout. If you don't understand felx layout, you can see an article by Ruan 1feng:

http://www.ruanyifeng.com/blog/2015/07/flex-grammar.html?utm_source=tuicool

Of course, there are a lot of information on the Internet, you can also search by yourself. The above is just a code example, which should be modified according to your own situation in the actual project.

Ok, let's talk about it first today, and the later part will explain the implementation of the title bar with the return button.


Related articles: