React顶层API

102 阅读2分钟
组件
React.Component & React.PureComponent
  • 两者的区别在于React.Component 并未实现 shouldComponentUpdate(),而 React.PureComponent 中以浅层对比 prop 和 state 的方式来实现了该函数。
  • 使用 React.Component 阻止渲染组件的话需要增加 shouldComponentUpdate 函数去进行判断,而使用 React.PureComponent ,React会帮你进行浅比较去判断需不需要重新渲染组件
React.memo
  • 类组件避免重新渲染可以使用 PureComponent 或者增加生命周期函数 shouldComponentUpdate ,函数组件则可以使用 React.memo
创建React元素
createElement()
createFactory()
转换元素
cloneElement()
isValidElement()
  • 验证对象是否为 React 元素,返回值为 truefalse

  • React.isValidElement(object)

  • React.Children

Fragments
React.Fragment
  • React.Fragment 组件能够在不额外创建 DOM 元素的情况下,让 render() 方法中返回多个元素。你也可以使用其简写语法 <></>

    render() {
      return (
        <React.Fragment>
          Some text.
          <h2>A heading</h2>
        </React.Fragment>
      );
    }
    
Refs
React.createRef
  • 类组件中创建一个能够通过 ref 属性附加到 React 元素的 ref

    class MyComponent extends React.Component {
      constructor(props) {
        super(props);
    
        this.inputRef = React.createRef();
      }
    
      render() {
        return <input type="text" ref={this.inputRef} />;
      }
    
      componentDidMount() {
        this.inputRef.current.focus();
      }
    }
    
React.forwardRef
  • React.forwardRef 会创建一个React组件,这个组件能够将其接受的 ref 属性转发到其组件树下的另一个组件中

    const FancyButton = React.forwardRef((props, ref) => (
      <button ref={ref} className="FancyButton">
        {props.children}
      </button>
    ));
    
    // You can now get a ref directly to the DOM button:
    const ref = React.createRef();
    <FancyButton ref={ref}>Click me!</FancyButton>;
    

    在上述的示例中,React 会将 <FancyButton ref={ref}> 元素的 ref 作为第二个参数传递给 React.forwardRef 函数中的渲染函数。该渲染函数会将 ref 传递给 <button ref={ref}> 元素。

    因此,当 React 附加了 ref 属性之后,ref.current 将直接指向 <button> DOM 元素实例。

Suspense

Suspense 使得组件可以“等待”某些操作结束后,再进行渲染。目前,Suspense 仅支持的使用场景是:通过 React.lazy 动态加载组件。它将在未来支持其它使用场景,如数据获取等。

React.lazy
  • 定义一个动态加载的组件,依赖 <Suspense></Suspense> 组件

    import React, { Suspense } from 'react';
    
    const OtherComponent = React.lazy(() => import('./OtherComponent'));
    
    function MyComponent() {
      return (
        <div>
          <Suspense fallback={<div>Loading...</div>}>
            <OtherComponent />
          </Suspense>
        </div>
      );
    }
    

    fallback 属性接受任何在组件加载过程中你想展示的 React 元素

React.Suspense