内容简介:注: 本文说的 React16 是指当前最新版本 16.5.2 ,而不是指 16.0.0。很多特性都是在 16.0.0 之后陆陆续续加的,而不是在一次性在 16.0 加入的。特别是实例:之前已经有
注: 本文说的 React16 是指当前最新版本 16.5.2 ,而不是指 16.0.0。很多特性都是在 16.0.0 之后陆陆续续加的,而不是在一次性在 16.0 加入的。特别是 getDerivedStateFromProps
在 16.4.0 之后还改过一次。
createRef
实例: 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 ); }
以上所述就是小编给大家介绍的《React16的新特性(内附实例)》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!
猜你喜欢:- React 新特性 Hooks 讲解及实例(二)
- React 新特性 Hooks 讲解及实例(三)
- 以太坊DAPP[3]-博彩-react特性与博彩合约实例
- 使用ES6的新特性Proxy来实现一个数据绑定实例
- JVM指令分析实例三(方法调用、类实例)
- 通过实例入门Golang
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Parsing Techniques
Dick Grune、Ceriel J.H. Jacobs / Springer / 2010-2-12 / USD 109.00
This second edition of Grune and Jacobs' brilliant work presents new developments and discoveries that have been made in the field. Parsing, also referred to as syntax analysis, has been and continues......一起来看看 《Parsing Techniques》 这本书的介绍吧!