美文网首页
class组件和函数式组件

class组件和函数式组件

作者: 小冰山口 | 来源:发表于2024-01-01 22:50 被阅读0次

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;

打印顺序:


image.png
  • propsstate管理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;
image.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}`);

相关文章

  • 笔记-React-Hooks

    一、矛与盾的问题?(Class组件与函数式组件)   在 React 中 Class 组件好用还是函数式组件好用呢...

  • React Hooks

    前言 React中组件分为两大类:Class类式组件、函数式组件 React v16.8以前: Class类式组件...

  • React 入门 3:组件的诞生

    本篇关于组件的诞生,包括函数组件和 class 组件。简单组件用函数,复杂组件用 class。 组件的构想 (一)...

  • React Hook

    React 声明组件的方式 Class声明和函数式声明(无状态组件)。Class声明可以操作state、生命周期等...

  • React - 类组件创建

    React创建组件有两种方式 函数式组件 类组件函数式组件已经学过,现在看下类组件怎么写。 函数式组件和类组件区别...

  • React创建组件的两种方式

    1.创建组件两种方式 方式1.函数式组件 方式2.函数式组件--使用ES6的class来定义一个组件 本文目的仅仅...

  • React基础知识

    基本 React 中的组件分为函数组件和类组件区分的话,简单的组件我们就用函数,如果复杂就用 class;函数组件...

  • React Hook用法详解(6个常见hook)

    1、useState:让函数式组件拥有状态 用法示例: PS:class组件中this.setState更新是st...

  • React 中被忽略的函数组件(Functional Compo

    React中有两种组件:函数组件(Functional Components) 和类组件(Class Compon...

  • 组件类型(函数式组件和类组件)

    React中有两种组件:函数组件(Functional Components) 和类组件(Class Compon...

网友评论

      本文标题:class组件和函数式组件

      本文链接:https://www.haomeiwen.com/subject/pbtpndtx.html