• 當前位置:首頁 > IT技術 > 微信平臺 > 正文

    微信授權掃碼點餐-新特性React16
    2021-08-09 00:16:02

    React v16.0

    render 支持返回數組和字符串

    download:《微信授權掃碼點餐-新特性React16

    // 不需要再將元素作為子元素裝載到根元素下面
    render() {
      return [
        <li/>1</li>,
        <li/>2</li>,
        <li/>3</li>,
      ];
    }

    Error Boundaries

    React15 在渲染過程中遇到運行時的錯誤,會導致整個 React 組件的崩潰,而且錯誤信息不明確可讀性差。React16 支持了更優雅的錯誤處理策略,如果一個錯誤是在組件的渲染或者生命周期方法中被拋出,整個組件結構就會從根節點中卸載,而不影響其他組件的渲染,可以利用 error boundaries 進行錯誤的優化處理。

    class ErrorBoundary extends React.Component {
      state = { hasError: false };
    
      componentDidCatch(error, info) {
        this.setState({ hasError: true });
    
        logErrorToMyService(error, info);
      }
    
      render() {
        if (this.state.hasError) {
          return <h1>數據錯誤</h1>;
        }
        
        return this.props.children;
      }
    }

    createPortal

    createPortal 的出現為 彈窗、對話框 等脫離文檔流的組件開發提供了便利,替換了之前不穩定的 API unstable_renderSubtreeIntoContainer,在代碼使用上可以做兼容,如:

    const isReact16 = ReactDOM.createPortal !== undefined;
    
    const getCreatePortal = () =>
      isReact16
        ? ReactDOM.createPortal
        : ReactDOM.unstable_renderSubtreeIntoContainer;

    使用 createPortal 可以快速創建 Dialog 組件,且不需要牽扯到 componentDidMount、componentDidUpdate 等生命周期函數。

    并且通過 createPortal 渲染的 DOM,事件可以從 portal 的入口端冒泡上來,如果入口端存在 onDialogClick 等事件,createPortal 中的 DOM 也能夠被調用到。

    import React from 'react';
    import { createPortal } from 'react-dom';
    
    class Dialog extends React.Component {
      constructor() {
        super(props);
    
        this.node = document.createElement('div');
        document.body.appendChild(this.node);
      }
    
      render() {
        return createPortal(
          <div>
            {this.props.children}
          </div>,
          this.node
        );
      }
    }

    支持自定義 DOM 屬性

    以前的 React 版本 DOM 不識別除了 HTML 和 SVG 支持的以外屬性,在 React16 版本中將會把全部的屬性傳遞給 DOM 元素。這個新特性可以讓我們擺脫可用的 React DOM 屬性白名單。筆者之前寫過一個方法,用于過濾非 DOM 屬性?filter-react-dom-props,16 之后即可不再需要這樣的方法。

    本文摘自 :https://blog.51cto.com/u

    開通會員,享受整站包年服務
    国产呦精品一区二区三区网站|久久www免费人咸|精品无码人妻一区二区|久99久热只有精品国产15|中文字幕亚洲无线码