React-hook技术
为函数组件拓展功能
函数组件没有继承组件基类,不具有组件的行为 为了函数组件具有这些行为,使用hook方法对函数组件做拓展
1.使用状态数据
let [数据, 修改数据的方法(新的状态 数据)] = useState(默认数据值);
在函数组件中,用”修改数据方法“ 修改数据 函数组件进入存在期,更新虚拟DOM
2.使用生命周期方法
useEffect(fn) fn代表componentDidMount以及componentDidUpdate方法。
...hook 为函数组件拓展了大量功能

函数组件重写为类组件代价太大时使用,一般直接使用类组件
import React, {Component, useEffect, useState, createRef} from 'react';
import {render} from 'react-dom';
//点击button改变数据,在组件内部改变的数据是状态数据,函数组件没有状态数据
// 获取元素中内容可以使用ref
let refNew = createRef();
function App () {
// 拓展状态数据
let [num, addNum] = useState(0)
// 拓展生命周期
useEffect(() => {
console.log(refNew.current.innerHTML);
})
// refNew.current为空,return完毕之后才有数据,相当于类组件的compopnentWillMount和componentWillUpdate
console.log('app', refNew.current);
return (
<div>
<h1>app part</h1>
<button ref={refNew} onClick= { e => addNum(num+1)}>{num}</button>
</div>
)
}
render(<App></App>, app)

浙公网安备 33010602011771号