React16的新特性(內附例項) |
您所在的位置:网站首页 › react的特性 › React16的新特性(內附例項) |
注: 本文說的 React16 是指當前最新版本 16.5.2 ,而不是指 16.0.0。很多特性都是在 16.0.0 之後陸陸續續加的,而不是在一次性在 16.0 加入的。特別是 getDerivedStateFromProps 在 16.4.0 之後還改過一次。 createRef例項: ofollow,noindex" target="_blank">https://stackblitz.com/edit/react16-ref 之前已經有 string ref (將被廢棄) 和 callback ref ,React16 新加入 createRef : // init this.btnRef = React.createRef(); // access this.btnRef.current new Context API例項: https://stackblitz.com/edit/react16-new-context // init const Context = React.createContext(); // use {value => { //... }} life cycle 新加入 componentDidCatch / getDerivedStateFromProps / getSnapshotBeforeUpdate 三種生命週期,並且將 componentWillMount / componentWillReceiveProps / componentWillUpdate 置為 UNSAFE 。 componentDidCatch例項: https://stackblitz.com/edit/react-componentdidcatch static getDerivedStateFromProps例項: https://stackblitz.com/edit/react-getderivedstatefromprops 在 元件例項化後 和 接受新 props 後被呼叫 ,需要 return 一個物件來更新狀態 或 返回null表示新的props不需要任何state更新 。 getSnapshotBeforeUpdate在react render()後的輸出被渲染到DOM之前被呼叫。 React.Fragment例項: https://stackblitz.com/edit/react16-fragments 一直以來,React render 只能 return 元件,不能是 string、 array、 boolean等值,這其實限制了開發者的能力。React 16 給我們帶來了這些新功能: // string render() { return 'this is string' } // number render() { return 123 } // boolean render() { return true && abc }另外,render return 要求一定要有一個根元件,而開發者就不得不在外層套一個 ,現在 React16 也給了我們方法: // 方法1: 返回 array,不過每一項必須有 key render() { return [ a, b, ] } // 方法2: React.Fragment render() { return ( a b ) } // 方法3: 其實還是 React.Fragment,不過是簡寫 render() { return ( a b ) } portal 例項: https://stackblitz.com/edit/react-portal-tips React.createPortal 可以讓開發者在元件中寫邏輯,而在頁面的別的位置渲染出來: render() { return ReactDOM.createPortal( this is a dialog , document.body ); }向我捐助 | 關於我 | 工作機會 |
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |