React - 组件

组件:接收任意入参,并返回 React 元素。

1. 函数组件

函数组件:接收唯一带有数据的 props 对象,并返回 React 元素。

function FunctionComponent(props) {
    return 
{ props.message }
}

2. class 组件

import React, { Component } from 'react'

class App extends Component {
    render() {
        return (
            
) } }

3. 组件组合

通过组合实现组件间代码重用

import React, { Component } from 'react'

class Test extends Component {
  render() {
    return (
        
{ this.props.children }
) } } class App extends Component { render() { return (

标题

段落

) } }

4. props

JSX 将自定义组件接收的属性转换为单个对象传递给组件,此对象就是 props 对象。

import React, { Component } from 'react'

class Test extends Component {
  constructor(props) {
    super(props)
    
    // 构造函数中使用 props:this.props.data
    
  }
  render() {
    
    // render 方法中使用:this.props.data
    
    return (
        
{ this.props.data }
) } }

5. state

import React, { Component } from 'react'

class Test extends Component {
  
  constructor() {
    super()
    
    this.handleClick = this.handleClick.bind(this)
    
    // 给 class 组件添加局部状态
    this.state = {
      title: '标题'
    }
  }
  
  render() {
    return (
        

{ this.state.title }

) } handleClick() { // 此处用来修改 state // 这种方式更改不会生效 this.state.title = '新标题' // 用来实时更改状态,但不是同步更改,此后不能保证获取到更新后的状态 this.setState({ // 参数对象会被浅合并到 state 中 title: '新标题' }) // 在最新状态后再次更新状态。state:目前最新状态;props:目前最新 props 对象 this.setState((state, props) => { return { title: '新标题' } // 返回值对象会和 state 进行浅合并 }) // 在更改状态之后,进行一系列操作 this.setState(() => {}, () => { // 此回调函数会在 state 完成合并后调用 // 建议使用 componentDidUpdate 生命周期函数替代 }) } }

6. 生命周期函数

React 组件生命周期.png
import React, { Component } from 'react'

class Test extends Component {
  
  // 用来初始化 state 和对方法进行 this 绑定。不要调用 this.setState 方法
  constructor() {
    super()
  }
  
  // class 组件中必须有 render 方法,此方法也是一个生命周期方法
  // 此方法被调用时会检查 state 和 props 的变化
  // 此方法应该为纯函数
  render() {
    return (
        
) } // 此方法会在组件挂载后立即调用,可以进行 Ajax 请求 // 适合添加订阅,需要在 componentWillUnmount 函数中取消订阅 componentDidMount() { } // 在渲染之前调用。nextProps:新的 props 对象;nextState:新的 state 状态 // 返回值为 false 会阻止重新渲染 // 可以使用 React.PureComponent 替代 React.Component 来实现此方法 shouldComponentUpdate(nextProps, nextState) { } // 组件更新后调用此方法,初次渲染不会调用 // 可以接收渲染前的 props 作为参数 // 可以通过比较现有 props 和新 props 对象决定是否进行一些操作 componentDidUpdate(prevProps) { } // 当组件从 DOM 中移除时调用 componentWillUnmount() { } }

7. 组件 API 和实例属性

API 属性
setState state
forceUpdate props

8. 组件规则

1. class 组件规则

  • 组件名称必须采用大驼峰命名方式。
  • React 组件必须保护 props 对象不被更改。
  • class 组件必须继承 React.Component。
  • class 组件中必须定义 render 函数。
  • 建议将 React 组件拆分为更小的组件。

2. 函数组件规则

  • 无状态,没有局部 state。
  • 无生命周期函数。
  • 没有 thisref

你可能感兴趣的:(React - 组件)