函數(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中的屬性比較相似,是用來組件之間單向傳值用的。
- 不需要提前聲明,組件傳值;
//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;