class 组件
- 有状态
(state)
, 每次都是修改的同一个状态 - 基于生命周期的管理
- 面向对象的好处: 易于理解, 适合新手
函数式组件
- 无状态, 每次刷新都是生成一个新的状态
- 基于状态变化的管理
- 函数式的好处: 简洁, 模版代码少, 易于复用
class组件生命周期和常规写法
-
class
组件的标准写法和组件的生命周期
import React from "react";
import { View } from "react-native";
class ClassView extends React.Component {
constructor(props) {
super(props);
console.log('constructor...');
}
// 生命周期
componentDidMount() {
console.log('componentDidMount...');
}
componentWillUnmount() {
console.log('componentWillUnmount...');
}
render() {
console.log('render...');
return (
<View style={{ width: 200, height: 200, backgroundColor: 'red'}}>
</View>
);
}
}
export default ClassView;
import React, { useEffect, useState } from 'react';
import type {PropsWithChildren} from 'react';
import ClassView from './src/components/ClassView';
import {
SafeAreaView,
ScrollView,
StatusBar,
StyleSheet,
Text,
useColorScheme,
View,
} from 'react-native';
import {
Colors,
DebugInstructions,
Header,
LearnMoreLinks,
ReloadInstructions,
} from 'react-native/Libraries/NewAppScreen';
type SectionProps = PropsWithChildren<{
title: string;
}>;
function App(): React.JSX.Element {
const [showClassView, setShowClassView] = useState(true);
// hook
useEffect( () => {
setTimeout(() => {
setShowClassView(false);
}, 2000);
}, [])
const isDarkMode = useColorScheme() === 'dark';
const backgroundStyle = {
backgroundColor: isDarkMode ? Colors.darker : Colors.lighter,
};
return (
<SafeAreaView style={backgroundStyle}>
<StatusBar
barStyle={isDarkMode ? 'light-content' : 'dark-content'}
backgroundColor={backgroundStyle.backgroundColor}
/>
<View style={styles.container}>
{ showClassView && <ClassView /> }
</View>
</SafeAreaView>
);
}
const styles = StyleSheet.create({
container: {
width: '100%',
flexDirection: 'row',
justifyContent: 'center',
alignItems: 'center'
},
});
export default App;
打印顺序:
![](https://img.haomeiwen.com/i2868984/b88e45c2ef2c5df7.png)
-
props
与state
管理ui
数据
props
import React, { useEffect, useState } from 'react';
import type {PropsWithChildren} from 'react';
import ClassView from './src/components/ClassView';
import {
SafeAreaView,
ScrollView,
StatusBar,
StyleSheet,
Text,
useColorScheme,
View,
} from 'react-native';
import {
Colors,
DebugInstructions,
Header,
LearnMoreLinks,
ReloadInstructions,
} from 'react-native/Libraries/NewAppScreen';
type SectionProps = PropsWithChildren<{
title: string;
}>;
function App(): React.JSX.Element {
// const [showClassView, setShowClassView] = useState(true);
// // hook
// useEffect( () => {
// setTimeout(() => {
// setShowClassView(false);
// }, 2000);
// }, [])
const isDarkMode = useColorScheme() === 'dark';
const backgroundStyle = {
backgroundColor: isDarkMode ? Colors.darker : Colors.lighter,
};
return (
<SafeAreaView style={backgroundStyle}>
<StatusBar
barStyle={isDarkMode ? 'light-content' : 'dark-content'}
backgroundColor={backgroundStyle.backgroundColor}
/>
<View style={styles.container}>
<ClassView name='jason' age={18} sex={true}/>
</View>
</SafeAreaView>
);
}
const styles = StyleSheet.create({
container: {
width: '100%',
flexDirection: 'row',
justifyContent: 'center',
alignItems: 'center'
},
});
export default App;
import React from "react";
import { View, Text } from "react-native";
class ClassView extends React.Component {
constructor(props) {
super(props);
}
// 生命周期
componentDidMount() {
console.log('componentDidMount...');
}
componentWillUnmount() {
console.log('componentWillUnmount...');
}
render() {
const {name, age, sex} = this.props;
console.log(`name=${name} age=${age} sex=${sex}`);
return (
<View style={{ width: '100%', height: 200, backgroundColor: 'red'}}>
<Text style={{color: 'white', fontSize: 20}}>
{`name=${name} age=${age} sex=${sex}`}
</Text>
</View>
);
}
}
export default ClassView;
![](https://img.haomeiwen.com/i2868984/7317af1e3fcbcc3d.png)
state和setState
import React from "react";
import { View, Text } from "react-native";
class ClassView extends React.Component {
constructor(props) {
super(props);
this.state = {
"address" : "广东省深圳市"
};
}
// 生命周期
componentDidMount() {
console.log('componentDidMount...');
setTimeout(() => {
this.setState(
{"address" : "广东省河源市"}
);
}, 2000);
}
componentWillUnmount() {
console.log('componentWillUnmount...');
}
render() {
const {name, age, sex} = this.props;
const {address} = this.state;
return (
<View style={{ width: '100%', height: 200, backgroundColor: 'cyan'}}>
<Text style={{color: 'white', fontSize: 20}}>
{`name=${name} age=${age} sex=${sex}`}
</Text>
<Text style={{color: 'black', fontSize: 25}}>
{`address=${address}`}
</Text>
</View>
);
}
}
export default ClassView;
props
是随着外部改变而改变的, state
是随着内部改变而改变的
函数式组件的优势和常用hook
- 函数式组件的3种写法
方法一
import React from "react";
import { View } from "react-native";
function FunctionView() {
return (
<View style={{ width: '100%', height: 200, backgroundColor: 'yellow'}}>
</View>
);
}
export default FunctionView
方法二:
import React from "react";
import { View } from "react-native";
const FunctionView = () => {
return (
<View style={{ width: '100%', height: 200, backgroundColor: 'yellow'}}>
</View>
);
}
export default FunctionView
方法三:
import React from "react";
import { View } from "react-native";
export default () => {
return (
<View style={{ width: '100%', height: 200, backgroundColor: 'yellow'}}>
</View>
);
}
- useState
const [address, setAddress] = useState("广东省深圳市");
- useEffect
useEffect(() => {
setTimeout(() => {
setAddress("湖北省宜昌市");
scrollViewRef.current.scrollToEnd({animated: false});
}, 2000);
}, []);
可以写多个useEffect
, 下面这个是监听address
, 其实参数是一个数组, 只要数组中的任何一个发生变化, 都会走回调
useEffect(() => {
console.log(address);
}, [address]);
- useRef
const scrollViewRef = useRef(null);
useEffect(() => {
setTimeout(() => {
setAddress("湖北省宜昌市");
scrollViewRef.current.scrollToEnd({animated: false});
}, 2000);
}, []);
return (
<View style={{ width: '100%', height: 200, backgroundColor: 'red'}}>
<Text style={{ fontSize: 20, color: 'yellow'}}>
{`name=${name} age=${age} sex=${sex} level=${level}`}
</Text>
<Text style={{ fontSize: 18, color: 'white'}}>
{ address }
</Text>
<ScrollView ref={scrollViewRef}>
<Text style={{ fontSize: 20, color: 'yellow', marginVertical: 12}}>
{`AAAAAA`}
</Text>
<Text style={{ fontSize: 20, color: 'yellow', marginVertical: 12}}>
{`BBBBBB`}
</Text>
<Text style={{ fontSize: 20, color: 'yellow', marginVertical: 12}}>
{`CCCCCC`}
</Text>
<Text style={{ fontSize: 20, color: 'yellow', marginVertical: 12}}>
{`DDDDDD`}
</Text>
<Text style={{ fontSize: 20, color: 'yellow', marginVertical: 12}}>
{`EEEEEE`}
</Text>
<Text style={{ fontSize: 20, color: 'yellow', marginVertical: 12}}>
{`FFFFFF`}
</Text>
<Text style={{ fontSize: 20, color: 'yellow', marginVertical: 12}}>
{`GGGGGG`}
</Text>
<Text style={{ fontSize: 20, color: 'yellow', marginVertical: 12}}>
{`HHHHHH`}
</Text>
<Text style={{ fontSize: 20, color: 'yellow', marginVertical: 12}}>
{`IIIIII`}
</Text>
</ScrollView>
</View>
);
- useWindowDimensions
const { width, height } = useWindowDimensions();
console.log(`width=${width} height=${height}`);
- useColorScheme
const colorScheme = useColorScheme();
console.log(`colorScheme=${colorScheme}`);
网友评论