react 开发
- 本质(虚拟DOM)
- 目的(高效渲染)
认知 (----简单实例)
- cnpm i react react-dom -s
- 在页面上引入这两个包 (react react-dom)
- react 创建组件,组件生命周期等
- react-dom 封装了和 DOM 操作相关 比如要把组件渲染到页面
- 使用 JS 创建DOM节点:
- 在 react 中,创建DOM元素,只能使用 react 提供的 js API, 不能直接手写html
- React.createElement() 方法,用于创建DOM 对象,接收三个及以上的参数
- 参数1.字符串类型的参数,表示创建的元素类型
- 参数2.是一个属性对象,表示 创建的元素上有哪些属性
- 参数3(....).表示当前元素的子节点 , 这个参数开始可以在后面放好多的虚拟DOM
var myH1 = React.createElement('h1',null,'这个是h1')
var myDiv = React.createElement('div',{title:'this is a div',id:'myDiv'},'这是一个div',myH1)
4.用 ReactDOM 实例把元素渲染页面指定的容器中
// ReactDOM.render('要渲染的虚拟DOM元素','要渲染到页面上的位置')
// ReactDOM.render('要渲染的虚拟DOM元素',document.getElementById('id'))
ReactDOM.render(myDiv,document.getElementById('app'))
生命周期
static defaultProps={}
this.state = {}
创建
ComponentWillMount: 组件将要挂载,
render: 创建虚拟DOM树,即将挂载到页面
ComponentDidMount: 挂载完成
运行
ComponentWillReceiveProps: 组件接收 新 的 Props 属性 只有外界传递给子组件的属性被修改的时候触发这个钩子函数
shouldComponentUpdate: 组件是否需要更新
ComponentWillUpdate: 组件要被更新,但还没更新。
render: 重新创建和渲染DOM树,把组件最新的state数据更新到 DOM树
ComponentDidUpdate: 组件更新完成,此时组件的数据是最新的
卸载
ComponentWillUnMount: 组件将要被卸载,但这是还是能正常使用
组件生命周期的执行顺序:
Mounting:
constructor()
componentWillMount()
render()
componentDidMount()
Updating:
componentWillReceiveProps(nextProps)
shouldComponentUpdate(nextProps, nextState)
componentWillUpdate(nextProps, nextState)
render()
componentDidUpdate(prevProps, prevState)
Unmounting:
componentWillUnmount()