1. 程式人生 > >React Native -- 建立元件的三種方式

React Native -- 建立元件的三種方式

1. React Native 建立元件的方式

React Native 建立元件有三種方式,分別是:

  1. ES6 建立元件 ( 推薦 )
  2. ES5 建立元件
  3. 函式式定義的無狀態元件

下面分別講下。

2. 建立元件

建立一個 HelloComponent.js 檔案,寫入元件。並在 App.js 中呼叫 HelloComponent 元件。 App.js 程式碼如下:

import React, {Component} from 'react';
import {Platform, StyleSheet, Text, View} from 'react-native';
import HelloComponent from './HelloComponent';

export default class App extends Component<Props> {
  render() {
    return (
      <View style={styles.container}>
        <HelloComponent/>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#F5FCFF'
  }
});

在 HelloComponent.js 檔案中分別使用三種方式建立元件:

方式一:ES6 建立元件 ( 推薦 )
import React, {Component} from 'react';
import {Platform, StyleSheet, Text, View} from 'react-native';

/**
 * 方式一:ES6
 * 推薦
 * 新建一個類,並匯出
 */
 export default class HelloComponent extends Component {
   render() {   //頁面渲染
     return <Text style={{fontSize:20, backgroundColor:'red'}}>Hellow</Text>
   }
 }

效果圖: 在這裡插入圖片描述

方式二:ES5 建立元件
 /**
  * 方式二:ES5
  * ES5 和 ES6 都需要 render 來渲染頁面
  * 區別在於 ES5 需要單獨匯出元件
  */
var HelloComponent=React.createClass({
  render() {  //頁面渲染
      return <Text style={{fontSize:20, backgroundColor:'red'}}>Hellow</Text>
    }
})
//匯出元件
module.exports=HelloComponent;

效果同方式一 ES5 和 ES6 區別:

  • 相同點: 都需要 render 來渲染頁面
  • 不同點: 區別在於 ES5 需要單獨匯出元件
方式 三:函式式定義
/**
 * 方式三:函式定義
 * 無狀態,不能使用this
 * 沒有生命週期方法
 */
function HelloComponent() {
  return <Text style={{fontSize:20, backgroundColor:'red'}}>Hellow</Text>
}
module.exports=HelloComponent;

效果同方式一

3. 訪問屬性

在 App.js 中的 HelloComponent 元件中傳入值 name:

export default class App extends Component<Props> {
  render() {
    return (
      <View style={styles.container}>
        <HelloComponent
          name='小明'
        />
      </View>
    );
  }
}
3.1 在無狀態元件裡訪問屬性:

在 HelloComponent 元件中呼叫:

function HelloComponent(props) {
  return <Text style={{fontSize:20, backgroundColor:'red'}}>Hellow.{props.name}</Text>
}
module.exports=HelloComponent;

效果如下: 在這裡插入圖片描述

3.2 在 ES6 裡訪問屬性:

ES6 通過 this 訪問屬性

export default class HelloComponent extends Component {
   render() { 
     return <Text style={{fontSize:20, backgroundColor:'red'}}>Hellow.{this.props.name}</Text>
   }
 }