React 组件 API

除了 JSX 语法,组件还对外暴露一组可在运行期调用的方法,统称组件 API:更新状态、强制刷新、访问 DOM、设置默认属性等。类组件时代这些方法写得很直观,函数组件用 Hooks 也能实现等价能力。

状态更新:setState(类组件)

setState 是类组件更新状态的入口,传入一个对象,React 会合并字段并触发重渲染:

this.setState({ count: this.state.count + 1 })

当新状态依赖旧状态时,可以传入函数形式,参数 prevState 一定是最新值:

this.setState(prevState => ({ count: prevState.count + 1 }))

函数组件中对应的是 useState 返回的 setter(见"组件状态"一章)。

强制更新:forceUpdate()

正常情况下改 state 就会自动重渲染;极少数想"不碰 state 也刷新"的场景可以调用 forceUpdate():

import { Component } from 'react'

class Clock extends Component {
  refresh = () => {
    this.forceUpdate() // 跳过 setState,强制重渲染一次
  }
  render() {
    return (
      <div>
        <p>现在时间:{new Date().toLocaleTimeString()}</p>
        <button onClick={this.refresh}>刷新时间</button>
      </div>
    )
  }
}

点击按钮即使没有状态变化,时间文本也会重新生成。日常开发应优先依赖 state 驱动渲染,forceUpdate 要少用。

访问 DOM:refs

通过 ref 可以拿到组件内部的真实 DOM 节点,用于聚焦输入框、测量尺寸、播放媒体等命令式操作:

import { Component, createRef } from 'react'

class FocusInput extends Component {
  inputRef = createRef()
  focusIt = () => this.inputRef.current.focus()
  render() {
    return (
      <div>
        <input ref={this.inputRef} />
        <button onClick={this.focusIt}>聚焦输入框</button>
      </div>
    )
  }
}

函数组件里则使用 useRef,把 ref 对象挂到元素的 ref 属性上,效果一致。

默认属性:defaultProps

用 defaultProps 给 props 设置默认值,父组件未传对应属性时自动生效:

class Button extends Component {
  render() {
    return <button>{this.props.text}</button>
  }
}

Button.defaultProps = {
  text: '点击我'
}

函数组件同样支持把 defaultProps 作为静态属性挂在函数上。

已废弃或慎用的旧 API

旧版文档中的 replaceState、setProps、isMounted 等 API 在新版 React 中已被移除或明确废弃,不要在新代码中使用。需要类似能力时,优先改用函数组件 + Hooks(useState、useRef、useEffect),这也是官方推荐的现代写法。

小结:类组件 API 的常用面是 setState、forceUpdate、refs 与 defaultProps 四类;认清已被废弃的旧 API,写新代码优先函数组件 + Hooks,能拿到更简洁的等价能力。

笔记加载中…