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

一、组件使用的场景

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

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

二、组件的基本用法

(1)未使用组件时

代码如下:

constructor(props) {
    super(props);
    this.state = {
      data:"这是一段没有使用另一个组件引入的代码块"
    };
  }
  render() {
    return (
      <div style={{width:"100%",height:"300px",fontSize:"20px"}}>
        <div style={{width:"100%",height:"100px",backgroundColor:"#ff0"}}></div>
        <div style={{width:"100%",height:"100px",fontSize:"12px",backgroundColor:"#0ff",textAlign:"center",lineHeight:"100px"}} onClick={()=>this.click()}>
          {this.state.data}
        </div>
        <div style={{width:"100%",height:"100px",backgroundColor:"#f0f"}}></div>
      </div>
    )
  }
  click=()=>{
    alert("点击到了!!!!");
  };

效果如下:

这里写图片描述

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={{width:"100%",height:"300px",fontSize:"20px"}}>
        <div style={{width:"100%",height:"100px",backgroundColor:"#ff0"}}></div>
        <MyScreen/>
        <div style={{width:"100%",height:"100px",backgroundColor:"#f0f"}}></div>
      </div>
    )
  }
}
export default Home
MyScreen.js部分代码:
import React,{ Component } from 'react'
class MyScreen extends Component {
  constructor(props) {
    super(props);
    this.state = {
      data:"这是一段没有使用另一个组件引入的代码块"
    };
  }
  render() {
    return (
      <div style={{width:"100%",height:"100px",fontSize:"12px",backgroundColor:"#0ff",textAlign:"center",lineHeight:"100px"}} onClick={()=>this.click()}>
        {this.state.data}
      </div>
    )
  }
  click=()=>{
    alert("点击到了!!!!");
  };
}
export default MyScreen

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

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

猜你喜欢

转载自blog.csdn.net/wuzhiwei_77/article/details/81564994