Skip to content
MiTu

MiTu

A Web developer who loves to Reading and photography

组件

简介

React 项目是由一个一个的组件组成的。

我们可以使用一个类继承 React.Component 实现一个组件,也可以使用函数式组件。

一个 React 组件包含几个部分:

state,props,方法(类方法和箭头函数方法),render 属性,生命周期属性

子组件标签要大写,小写的会被解析成原生标签

父子组件通信

父子组件通信主要有 3 种方式

props 传递属性、props 传递回调、父组件通过 ref 属性获取子组件的引用

jsx
import React from 'react';
import PropTypes from 'prop-types';

class Child extends React.Component {
  name = 'child';
  static propTypes = {
    digit: PropTypes.number.isRequired
  };

  render() {
    <div>
      <span>digit:{this.props.digit}</span>
      <button onClick={this.props.onButtonClick}>点击</button>
    </div>;
  }
}

class App extends React.Component {
  state = {
    digit: 0
  };

  childNode = React.createRef();

  onButtonClick = () => {
    this.state({
      digit: Math.random()
    });

    console.log(this.childNode.current.name);
  };

  render() {
    return (
      <div>
        <Child
          ref={this.childNode}
          digit={this.state.digit}
          onButtonClick={this.onButtonClick}
        />
      </div>
    );
  }
}

export default App;

props 父组件给子组件传递,子组件接收,类型校验

  1. 父组件在 JSX 元素上通过属性传递给子组件,子组件通过 this.props 来访问父组件传递的属性
  2. 类型校验:propTypes 属性和 defaultProps 属性

回调

回调其实是父组件通过 props 传递给子组件的一个函数,子组件可以在组件内部调用这个函数

ref 一般用在父组件直接调用子组件的方法的场景

父组件通过 ref 获取子组件的实例的引用,使用步骤如下:

  1. react.createRef
  2. 子组件元素设置 ref 属性
  3. 使用时候用 current 访问

生命周期

生命周期钩子函数用来在组件从创建到销毁的某个阶段做一些逻辑。

常见的生命周期钩子函数有 ComponentDidMount、ComponentWillUnmount 等

通常在 componentDidMount 中处理开启定时器、注册监听器。在 componentWillUnmount 钩子中清除定时器、注销监听器。