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 <Context.Provider value={/*...*/}> <Context.Consumer> {value => { //... }} </Context.Consumer>
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 && <div>abc</div> }
另外,render return 要求一定要有一個根元件,而開發者就不得不在外層套一個 <div>
,現在 React16 也給了我們方法:
// 方法1: 返回 array,不過每一項必須有 key render() { return [ <h1 key="a">a</h1>, <h1 key="b">b</h1>, ] } // 方法2: React.Fragment render() { return ( <React.Fragment> <h1>a</h1> <h1>b</h1> </React.Fragment> ) } // 方法3: 其實還是 React.Fragment,不過是簡寫 render() { return ( <> <h1>a</h1> <h1>b</h1> </> ) }
portal
例項: https://stackblitz.com/edit/react-portal-tips
React.createPortal
可以讓開發者在元件中寫邏輯,而在頁面的別的位置渲染出來:
render() { return ReactDOM.createPortal( <div> this is a dialog </div>, document.body ); }