react16
2019-07-17 14:00
435 查看
版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/qq_35423431/article/details/95944195
下载包
react:核心库,包含生成虚拟dom的react.createElement函数以及继承的Component类
react-dom:核心功能是将虚拟dom渲染成实际的dom
babel-eslint:es6转es5,兼容不支持es6的浏览器,并且babel内嵌了对JSX的支持
2、setState执行机制
class Example extends React.Component { constructor() { super(); this.state = { val: 0 }; } componentDidMount() { this.setState({val: this.state.val + 1}); console.log(this.state.val); // 第 1 次 log this.setState({val: this.state.val + 1}); console.log(this.state.val); // 第 2 次 log setTimeout(() => { this.setState({val: this.state.val + 1}); console.log(this.state.val); // 第 3 次 log this.setState({val: this.state.val + 1}); console.log(this.state.val); // 第 4 次 log }, 0); } render() { return null; } };
输出结果:0,0,2,3
在React的setState函数实现中,会根据一个变量 isBatchingUpdate 来判断是直接同步更新this.state还是放到队列中异步更新 。React使用了事务的机制,React的每个生命周期和合成事件都处在一个大的事务当中。在事务的前置钩子中调用batchedUpdates方法修改isBatchingUpdates变量为true,在后置钩子中将变量置为false。在此执行setState不会立即执行,会将修改状态放入队列中,将多次状态合成一次进行修改。在原生事件绑定和setTimeout异步的函数中,引发后置钩子触发,所以此时的setState会直接进入非批量更新模式,表现在我们看来成为了同步SetState。
1、ref
在react的自上而下的数据流中,父子组件交互是通过props实现的。state或者props改变,会导致子组件重新渲染。子组件调用父组件的方法,可以使用this.props.handle()。
实际中也会有父组件需要调用子组件方法的场景,这时就需要使用refs。两种方式使用:
PS:不能在函数组件上使用 ref 属性,因为他们没有实例
React.createRef()React.createRef()( React 16.3 版本引入)
回调Refs
class MyComponent extends React.Component { constructor(props) { super(props); this.myRef = React.createRef(); } componentDidMount(){ // 调用子组件的方法 this.myRef.current.focusTextInput(); } render() { return <ChildComponent ref={this.myRef} />; } }回调Refs
class MyComponent extends React.Component { constructor(props) { super(props); this.myRef = el => { this.textInput = el }; } render() { return <ChildComponent ref={el => this.myRef = el} />; } }
class MyComponent extends React.Component { constructor(props) { super(props); this.myRef = el => { this.textInput = el }; } render() { return <ChildComponent ref={this.myRef} />; } }
不能在函数组件上使用,因为没有实例。
相关文章推荐
- react-native试玩(16)-iOS分段控制控件
- 16、react之 MIxin
- React 16.x折腾记 - (4) 侧边栏联动Tabs菜单-增强版(结合Mobx)
- 目前最新《React16+React-Router4 从零打造企业级电商后台管理系统》
- react爬坑记16---reflux
- React 16.x折腾记 - (7) 基于React+Antd封装聊天记录(用到React的memo,lazy, Suspense这些)
- 《React-Native系列》16、 RN组件之ListView
- React 16.x折腾记 - (10) UmiJS 2.x + antd 重写后台管理系统记录的问题及解决姿势
- 夺命雷公狗-----React---16--事件操作事件
- React 版本16以后,PropsTyple被独立出来了。
- React 16 服务端渲染的新特性
- React16+Redux 实战企业级大众点评WebApp
- React 16.x折腾记 - (9) 基于Antd+react-router-breadcrumbs-hoc封装一个小巧的面包屑组件
- react 16新特性介绍
- [React] Render Text Only Components in React 16
- React 16.x折腾记 - (2) 实现路由动效过渡,并解决过程中奇奇怪怪的问题
- 【React Native开发】React Native控件之Switch开关与Picker选择器组件讲解以及使用(16)
- Facebook 让步: React 协议改为 MIT,下周随 React 16一同发布
- 基于react16 webpack3 搭建前端spa基础框架 react-router的4种异步加载方式
- React16+React-Router4 从零打造企业级电商后台管理系统