• 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>
        );
      }
    }
  • 相关阅读:
    九种常用排序的性能分析总结
    C语言输出格式总结
    线程安全的单例模式
    反射原理
    二进制的计算(计算机为什么采用补码存储数据)
    java程序员必须会的技能
    09网易校园招聘笔试题
    Spring获取ApplicationContext方式,和读取配置文件获取bean的几种方式
    【转】策略与机制分离
    VM PowerCli的简单安装和使用学习
  • 原文地址:https://www.cnblogs.com/yangshifu/p/12508187.html
Copyright © 2020-2023  润新知