zoukankan      html  css  js  c++  java
  • React 自定义组件的两种方式

    React 自定义组件的两种方式:

    函数组件和类组件

     

    第一种,函数组件(无状态,即无私有属性,state):

    function Welcome(props) {
      return <h1>Hello, {props.name}</h1>;
    }

    第二种,类(ES6)组件(有状态。即有私有属性,state):

    class Welcome extends React.Component {
      render() {
        return <h1>Hello, {this.props.name}</h1>;
      }
    }

    一般完整的类组件,示例:

    import React, { Component } from "react"; 

    class Hello extends Component {

    // 构造函数
    constructor(props){
    super(props);

    // 声明私有数据 (类似vue中data的作用)
    this.state = { msg:'123' }
    }
    render() {
    console.log(this.state)
    // 打印查看
    return (
    <div>
    {/* 在组件中使用私有数据 */}
    <h1>{this.state.msg}</h1>
    </div> );
    }
    }
    export default Hello;

    什么情况下使用有状态组件?什么情况下使用无状态组件?

    如果组件内,不需要有私有的数据,即不需要  state,此时,使用函数创建无状态组件比较合适;
    如果组件内,需要有自己私有的数据,即需要  state,则,使用 class 关键字 创建有状态组件比较合适;

    组件中的 props 和 state 之间的区别

    props 中存储的数据,都是外界传递到组件中的;
    props 中的数据,都是只读的;
    state 中的数据,都是组件内私有的;
    state 中的数据,都是可读可写的;
    props 在 有状态组件 和 无状态组件中,都有;
    state 只有在 有状态组件中才能使用;无状态组件中,没有 state;

    关于ES6类的继承和this以及props的问题,请看:https://www.cnblogs.com/zqblog1314/p/12902707.html

  • 相关阅读:
    简单粗暴,微生物生态研究中常用数据库简介--转载
    sliva数据库简介--转载
    DriverDBv2---人类肿瘤driver基因数据库
    lncrnablog
    胞外囊泡与外泌体数据库--转载
    Oncomine: 一个肿瘤相关基因研究的数据库--转载
    circRNA研究手册
    常用Gene ID转换工具--转载
    miRNA几大常用的数据库
    zk使用通知移除节点
  • 原文地址:https://www.cnblogs.com/zqblog1314/p/12905423.html
Copyright © 2011-2022 走看看