zoukankan      html  css  js  c++  java
  • React.Component 和 funtion 组件的区别

    结论:需要根据state进行渲染时,使用React.Component;用不到state时,可以直接写函数组件。

    Function 函数组件:可以接收入参(props),通过return返回dom结构。

    function Hello(props) {
        return <h1>Hello, {props.name}!</h1>;
    }
     
    ReactDOM.render(
        <Hello name="Jack" />, 
        document.getElementById('root')
    );

    React.Component 是一个class(类),不止可以接收props,也支持state,还包含了生命周期函数,在render函数内返回dom结构。

    class Hello extends React.Component {
        constructor(props) {
            super(props);
            this.state = {
                myname:""
            };
        }
    
        componentDidMount(){
            this.setState({
                myname:"baby"
            })
        }
    
        render() {
            return (
                <div>
                    <h1>Hello, {this.props.name}!</h1>
                    <h1>I am {this.state.myname}</h1>
                </div>
            );
        }
    }
    
    ReactDOM.render(
        <Hello name="Jack" />,
        document.getElementById('root')
    );

    Hook 是React的新特性,通过 useState 和 EffectState 方法,让函数组件也支持了state。

    // Hook写法
    import React, { useState, useEffect } from 'react';
    
    function Example() {
      const [count, setCount] = useState(0);
    
      useEffect(() => {
        document.title = `You clicked ${count} times`;
      });
    
      return (
        <div>
          <p>You clicked {count} times</p>
          <button onClick={() => setCount(count + 1)}>
            Click me
          </button>
        </div>
      );
    }
    
    // 对应Class写法
    class Example extends React.Component {
      constructor(props) {
        super(props);
        this.state = {
          count: 0
        };
      }
    
      componentDidMount() {
        document.title = `You clicked ${this.state.count} times`;
      }
    
      componentDidUpdate() {
        document.title = `You clicked ${this.state.count} times`;
      }
    
      render() {
        return (
          <div>
            <p>You clicked {this.state.count} times</p>
            <button onClick={() => this.setState({ count: this.state.count + 1 })}>
              Click me
            </button>
          </div>
        );
      }
    }
  • 相关阅读:
    《构建之法》阅读笔记二
    《构建之法》阅读笔记一
    软件工程个人课程总结
    纯随机数生成器
    递归方法
    素数的输出
    字母统计|英语的26 个字母在一本小说中是如何分布的
    类的声明
    FileInputStream类与FileOutputStream类
    验证码|程序登录界面
  • 原文地址:https://www.cnblogs.com/yangshifu/p/12508187.html
Copyright © 2011-2022 走看看