React的顶层API有哪些?

一、简介

React库提供了如下API,可直接调用。


二、创建元素
1、createElement()
  • 功能:创建 React 元素。

    // 函数原型
    React.createElement(
        type,
        [props],
        [...children]
    )
    
  • 两种创建元素的方式:

    • 使用JSX来创建元素,不需要调用createElement(),预处理器babel会处理

      // 使用jsx创建元素和组件
      class Hello extends React.Component {
          render() {
              return <div>Hello {this.props.toWhat}</div>;
          }
      }
      
      ReactDOM.render(
          <Hello toWhat="World" />,
          document.getElementById('root')
      );
      
    • 不使用JSX来创建元素,就需要调用createElement()

      // 不使用jsx创建元素和组件
      class Hello extends React.Component {
          render() {
              return React.createElement('div', null, `Hello ${this.props.toWhat}`);
          }
      }
      
      ReactDOM.render(
          React.createElement(Hello, { toWhat: 'World' }, null),
          document.getElementById('root')
      );
      

三、元素操作API
1、cloneElement()
  • 功能:复制生成一个新元素。

    // 函数原型
    React.cloneElement(
        element,
        [config],
        [...children]
    )
    // config :含新的 props,key 或 ref
    
  • 等同于jsx

    React.cloneElement()
    // 几乎等同于下面jsx写法
    < element.type {...element.props } {...props }> { children }</element.type >
    

2、isValidElement()

验证对象是否为 React 元素,返回值为 truefalse

React.isValidElement(object)

四、子元素操作API

React.Children功能:可以遍历访问子元素,同时可以访问到属性 this.props.children ,无法访问到的数据。

1、React.Children.map
  • 功能:遍历子元素,并返回一个数组。函数原型如下:

    React.Children.map(children, function)
    
  • 使用实例:遍历并复制子元素

    const Child = () => (
        <div>child</div>
    )
    
    class App extends React.Component {
        render() {
            const template1 = React.Children.map(this.props.children, (child) => {
                return React.cloneElement(child);
            });
    
            return template1;
        }
    }
    
2、React.Children.forEach
  • 功能:与React.Children.map一样作用,区别是返回值不是数组。

    React.Children.forEach(children, function)
    
3、React.Children.count
  • 功能:返回 children 中的组件总数量,等同于通过 map 或 forEach 调用回调函数的次数。

    React.Children.count(children)
    
4、React.Children.only
  • 功能:验证 children 是否只有一个子节点(React元素),如果有则返回它,否则此方法会抛出错误。

    React.Children.only(children)
    
  • 注意点:React.Children.only() 不接受 React.Children.map() 的返回值,因为它是一个数组而并不是 React 元素。


五、组件相关API
1、React.Component
  • 功能:使用 ES6 classes 方式定义 React 组件的基类:

    class Greeting extends React.Component {
        render() {
            return <h1>Hello, {this.props.name}</h1>;
        }
    }
    

2、React.PureComponent
  • 功能:与React.Component 一样,都可以继承他们来实现组件。

  • 区别:React.PureComponent 实现了 shouldComponentUpdate(),而 React.Component 没有。React.PureComponent 只有在 prop 和 state 数据变化时,才进行组件渲染,可用于组件性能优化。

  • 两点注意:

    • 确定 prop 和 state 数据是否变化时,会进行比较操作,这个比较操作只适合简单数据结构,不适用于复杂数据结构,请确保 prop 和state 对象不是复杂数据结构。

    • 确保 子组件 也都继承 React.PureComponent。


3、React.memo
  • 功能:是一个高阶组件,可以包裹其他组件来提高性能。

  • 原理:React.memo 会监控组件的 props 属性的变化,只有变化才重新渲染,否则跳过渲染操作。

    const MyComponent = React.memo(function MyComponent(props) {
        /* 使用 props 渲染 */
    });
    
  • 两点注意:

    • 如果 React.memo 组件中使用了 useState、useContext,那么state、context 数值改变时,React.memo 组件也会重新渲染。

    • React.memo 无法监控复杂数据结构props的变化,需要自定义比较函数来实现对复杂数据结构的监控。

      function MyComponent(props) {
          /* 使用 props 渲染 */
      }
      function areEqual(prevProps, nextProps) {
          /*
          如果把 nextProps 传入 render 方法的返回结果与
          将 prevProps 传入 render 方法的返回结果一致则返回 true,
          否则返回 false
          */
      }
      export default React.memo(MyComponent, areEqual);
      

六、延迟加载

渲染页面时,可以不加载未用到的组件。

1、React.lazy
  • 功能:延迟加载未用到的组件,依赖 React.Suspense

    // 这个组件是动态加载的
    const SomeComponent = React.lazy(() => import('./SomeComponent'));
    
  • 注意:使用 React.lazy 的动态引入特性需要 JS 环境支持 Promise。在 IE11 及以下版本的浏览器中需要通过引入 polyfill 来使用该特性。


2、React.Suspense
  • 名称:指定加载指示器(loading indicator)

  • 功能:配合上 React.lazy 完成延迟加载。

    // 该组件是动态加载的
    const OtherComponent = React.lazy(() => import('./OtherComponent'));
    
    function MyComponent() {
        return (
            // 显示 <Spinner> 组件直至 OtherComponent 加载完成
            <React.Suspense fallback={<Spinner />}>
                <div>
                    <OtherComponent />
                </div>
            </React.Suspense>
        );
    }
    

七、其他API
1、React.Fragment
  • 功能:不额外创建 DOM 元素的情况下,让 render() 返回多个元素。使用详情,看这里

2、React.createRef
  • 功能:创建 ref 对象,指向组件,让其他组件方便访问其内部数据和方法。使用详情,看这里

3、React.forwardRef
  • 功能:React.forwardRef 会创建一个React组件,新组件可以把传递进来的 ref 对象,转发给子元素。
  • 两种使用场景:转发 refs 到 DOM 组件在高阶组件中转发 refs。详情,看这里

八、参考文档:
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值