• react.js从入门到精通(四)——组件的基本使用


    一、组件使用的场景

    (1)一个.js文件中代码量过大,不好维护。

    (2)某些功能或样式在项目中大范围使用,组件起到了封装代码的作用。

    二、组件的基本用法

    (1)未使用组件时

    代码如下:

    constructor(props) {
        super(props);
        this.state = {
          data:"这是一段没有使用另一个组件引入的代码块"
        };
      }
      render() {
        return (
          <div style={{"100%",height:"300px",fontSize:"20px"}}>
            <div style={{"100%",height:"100px",backgroundColor:"#ff0"}}></div>
            <div style={{"100%",height:"100px",fontSize:"12px",backgroundColor:"#0ff",textAlign:"center",lineHeight:"100px"}} onClick={()=>this.click()}>
              {this.state.data}
            </div>
            <div style={{"100%",height:"100px",backgroundColor:"#f0f"}}></div>
          </div>
        )
      }
      click=()=>{
        alert("点击到了!!!!");
      };
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20

    效果如下:

    这里写图片描述

    2、使用组件引入方式

    代码如下:

    Home.js部分代码:
    import React,{ Component } from 'react'
    import MyScreen from "./MyScreen";
    class Home extends Component {
      constructor(props) {
        super(props);
        this.state = {
    
        };
      }
      render() {
        return (
          <div style={{"100%",height:"300px",fontSize:"20px"}}>
            <div style={{"100%",height:"100px",backgroundColor:"#ff0"}}></div>
            <MyScreen/>
            <div style={{"100%",height:"100px",backgroundColor:"#f0f"}}></div>
          </div>
        )
      }
    }
    export default Home
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    MyScreen.js部分代码:
    import React,{ Component } from 'react'
    class MyScreen extends Component {
      constructor(props) {
        super(props);
        this.state = {
          data:"这是一段没有使用另一个组件引入的代码块"
        };
      }
      render() {
        return (
          <div style={{"100%",height:"100px",fontSize:"12px",backgroundColor:"#0ff",textAlign:"center",lineHeight:"100px"}} onClick={()=>this.click()}>
            {this.state.data}
          </div>
        )
      }
      click=()=>{
        alert("点击到了!!!!");
      };
    }
    export default MyScreen
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20

    效果与上面的完全一样,点击事件也能实现。

    注意:一个新的组件同样具备完整的生命周期。

  • 相关阅读:
    加解密工具类(含keystore导出pfx)
    Java使用数字证书加密通信(加解密/加签验签)
    关于javax.crypto.BadPaddingException: Blocktype错误的几种解决方法
    产生定长的随机数
    数字证书生成--加密密/加签验签
    随机指定范围内N个不重复的数
    sql2012还原sql2008备份文件语句
    uploadify API
    海量数据处理分析
    .net经验积累
  • 原文地址:https://www.cnblogs.com/xukun588/p/9458675.html
Copyright © 2020-2023  润新知