English 中文(简体)
React Native - Styling
  • 时间:2024-12-27

React Native - Stypng


Previous Page Next Page  

There are a couple of ways to style your elements in React Native.

You can use the style property to add the styles inpne. However, this is not the best practice because it can be hard to read the code.

In this chapter, we will use the Stylesheet for stypng.

Container Component

In this section, we will simppfy our container component from our previous chapter.

App.js

import React from  react ;
import { StyleSheet, Text, View } from  react-native ;
import PresentationalComponent from  ./PresentationalComponent 

export default class App extends React.Component {
   state = {
      myState:  This is my state 
   }
   render() {
      return (
         <View>
            <PresentationalComponent myState = {this.state.myState}/>
         </View>
      );
   }
}

Presentational Component

In the following example, we will import the StyleSheet. At the bottom of the file, we will create our stylesheet and assign it to the styles constant. Note that our styles are in camelCase and we do not use px or % for stypng.

To apply styles to our text, we need to add style = {styles.myText} property to the Text element.

PresentationalComponent.js

import React, { Component } from  react 
import { Text, View, StyleSheet } from  react-native 

const PresentationalComponent = (props) => {
   return (
      <View>
         <Text style = {styles.myState}>
            {props.myState}
         </Text>
      </View>
   )
}
export default PresentationalComponent

const styles = StyleSheet.create ({
   myState: {
      marginTop: 20,
      textApgn:  center ,
      color:  blue ,
      fontWeight:  bold ,
      fontSize: 20
   }
})

When we run the app, we will receive the following output.

React Native Stypng Advertisements