zoukankan      html  css  js  c++  java
  • 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

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

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

  • 相关阅读:
    Linux下的目录结构
    VM
    代码命名规范
    java环境及配置
    Code::Blocks 使用Cygwin编译加调试
    vscode使用体会
    openwrt编译笔记
    ubuntu20 使用root登录
    程序员如何更好的表达自己的想法- Graphviz:关系图脚本绘制工具-转
    编译codelite心得
  • 原文地址:https://www.cnblogs.com/xukun588/p/9458675.html
Copyright © 2011-2022 走看看