React Native入門 - 函數(shù)組件,class組件 ,props ,state

函數(shù)組件只需要接受props參數(shù)并且返回一個React元素,class組件需要繼承component,還需要創(chuàng)建render 并且返回React元素,語法看起來麻煩點。

函數(shù)組件沒有this,沒有生命周期,沒有狀態(tài)state。

類組件有this,有生命周期,有狀態(tài)state。

類組件:

import React,{Component} from 'react'
import {View,Text} from 'react-native'
export default class App extends Component{
    render(){
        return(
                <View>
                    <Text >Hello Word</Text>
                </View>
        )
    }
}

函數(shù)組件:

import React,{Component} from 'react'
import {View,Text} from 'react-native'
const SiteNameComponent = (props) => {
   return (
      <View>
         <Text >Hello Word </Text>
      </View>
   )
}

props理解

props 和我們OC中的屬性比較相似,是用來組件之間單向傳值用的。

  1. 不需要提前聲明,組件傳值;
//classA組件
export class classA extends Component {
  render() {
    return (<Text>Hello {this.props.name}!</Text>);
  }
}

//classB組件
export class classB extends Component {
  render() {
    return (
      <View style={{alignItems: 'center'}}>
        //調(diào)用classA組件,并對name變量賦值
        <classA name='Hello Word' />
      </View>
    );
  }
}

2.組件中必須包含某種變量類型的某變量,就要用到PropTypes做聲明;
3.可以設置默認值;

export class classA extends Component {
  static propTypes: {
    //設置title變量的類型
    title: React.PropTypes.string.isRequired,
  },
static defaultProps = {  
   title:'Hello Word',  
 }  
  render() {
     return (
        <View>
          <Text>  {this.props.title} </Text>
        </View>
     );
  }
}

state

react中的函數(shù)組件通常只考慮負責UI的渲染,沒有自身的狀態(tài)沒有業(yè)務邏輯代碼,是一個純函數(shù)。它的輸出只由參數(shù)props決定,不受其他任何因素影響。為了解決給函數(shù)組件加狀態(tài),可以使用Hooks技術實現(xiàn)。
1)useState 使用

import React, { Component, useState } from "react";
import { View,StyleSheet, TextInput,Text } from "react-native";

const UselessTextInput = () =>  {
//使用Hooks技術添加value狀態(tài),并設置默認值
  const [value,setValue] = useState('rfradsfdsf')

  return (
    <View style={styles.container}>
      <TextInput
        style={{ height: 40}}
        placeholder='請輸入用戶名'
        onChangeText={(text)=>{
          setValue(text)
        }}
        value={value}
      />
      <Text>{value}</Text>
   </View>
  );
}
const styles = StyleSheet.create({
  container: {
    paddingTop: 50,
    backgroundColor: '#ffffff',
    borderBottomColor: '#000000',
    borderBottomWidth: 1,
  },
});
export default UselessTextInput;
?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容