React

react render 渲染函数

2023-10-09  本文已影响0人  暴躁程序员

一、render 函数的渲染过程

  1. 在 render 函数中编写 JSX 模板
render() {
  return (
    <>
      <div style={{color: "red"}}>
          <h1> 父组件 </h1>
          <div> hello world </div>
      </div>
    </>
  );
}
  1. jsx 模板通过 babel 编译成 createElement 对象用于创建虚拟dom元素
React.createElement(
  "div",
  {
    style: { color: "red" },
  },
  React.createElement("h1", null, "父组件"),
  React.createElement("div", null, "hello world")
);
  1. 将虚拟dom元素转化成真实DOm元素

二、类、函数组件中的 render 函数

  1. 在类组件中的 render 函数
import React, { Component } from "react";

class Test extends Component {
  constructor(props) {
    super(props);
    this.state = {};
  }
  render() {
    console.log("render 函数");
    return (
      <>
        <div>hello world</div>
      </>
    );
  }
}
export default Test;
  1. 在函数组件中,函数组件的 render 函数是函数本身
function Test(props) {
  console.log("render 函数");
  return (
    <>
      <div>hello world</div>
    </>
  );
}
export default Test;

三、类、函数组件 render 函数的执行时机

1. 在函数、类组件创建时执行
2. 在函数、类组件的 props、state 状态更新时执行 
  1. 在父组件中,实现类组件的 state 状态变更
import React, { Component } from "react";
import OptimizeChildView from "./OptimizeChildView"
class Test extends Component {
  constructor(props) {
    super(props);
    this.state = {
        num: 1
    };
    this.changeNum = this.changeNum.bind(this)
  }
  render() {
    console.log("父组件 render 函数");
    return (
      <>
        <h1>父组件</h1>
        <div>{this.state.num}</div>
        <button onClick={this.changeNum}>改变子组件 props</button>
        <hr />
        <OptimizeChildView num={this.state.num}/>
      </>
    );
  }
  changeNum(){
    this.setState({
        num: this.state.num + 1
    })
  }
}
export default Test;
  1. 在子组件中,实现函数组件的props、state状态变更
import React from "react";
import { useState } from "react";
function Test(props) {
  console.log("子组件 render 函数");
  const [count, setCount] = useState(100);
  return (
    <>
      <h1>子组件</h1>
      <div>props.num:{props.num}</div>
      <div>state.num:{count}</div>
      <button onClick={()=>{setCount(count+1)}}>改变函数组件 state</button>
    </>
  );
}
export default Test;
上一篇 下一篇

猜你喜欢

热点阅读