(1). Hook是React 16.8.0版本增加的新特性/新语法
(2). 可以让你在函数组件中使用 state 以及其他的 React 特性
(1). State Hook: React.useState()
(2). Effect Hook: React.useEffect()
(3). Ref Hook: React.useRef()
(1). State Hook让函数组件也可以有state状态, 并进行状态数据的读写操作
(2). 语法: const [xxx, setXxx] = React.useState(initValue)
(3). useState()说明:
参数: 第一次初始化指定的值在内部作缓存
返回值: 包含2个元素的数组, 第1个为内部当前状态值, 第2个为更新状态值的函数
(4). setXxx()2种写法:
setXxx(newValue): 参数为非函数值, 直接指定新的状态值, 内部用其覆盖原来的状态值
setXxx(value => newValue): 参数为函数, 接收原本的状态值, 返回新的状态值, 内部用其覆盖原来的状态值
(1). Effect Hook 可以让你在函数组件中执行副作用操作(用于模拟类组件中的生命周期钩子)
(2). React中的副作用操作:
发ajax请求数据获取
设置订阅 / 启动定时器
手动更改真实DOM
(3). 语法和说明:
useEffect(() => {
// 在此可以执行任何带副作用操作
return () => { // 在组件卸载前执行
// 在此做一些收尾工作, 比如清除定时器/取消订阅等
}
}, [stateValue]) // 如果指定的是[], 回调函数只会在第一次render()后执行
(4). 可以把 useEffect Hook 看做如下三个函数的组合
componentDidMount()
componentDidUpdate()
componentWillUnmount()
(1). Ref Hook可以在函数组件中存储/查找组件内的标签或任意其它数据
(2). 语法: const refContainer = useRef()
(3). 作用:保存标签对象,功能与React.createRef()一样
1 import React from 'react'
2 import ReactDOM from 'react-dom'
3
4 //类式组件
5 /* class Demo extends React.Component {
6
7 state = {count:0}
8
9 myRef = React.createRef()
10
11 add = ()=>{
12 this.setState(state => ({count:state.count+1}))
13 }
14
15 unmount = ()=>{
16 ReactDOM.unmountComponentAtNode(document.getElementById('root'))
17 }
18
19 show = ()=>{
20 alert(this.myRef.current.value)
21 }
22
23 componentDidMount(){
24 this.timer = setInterval(()=>{
25 this.setState( state => ({count:state.count+1}))
26 },1000)
27 }
28
29 componentWillUnmount(){
30 clearInterval(this.timer)
31 }
32
33 render() {
34 return (
35 <div>
36 <input type="text" ref={this.myRef}/>
37 <h2>当前求和为{this.state.count}</h2>
38 <button onClick={this.add}>点我+1</button>
39 <button onClick={this.unmount}>卸载组件</button>
40 <button onClick={this.show}>点击提示数据</button>
41 </div>
42 )
43 }
44 } */
45
46 function Demo(){
47 //console.log('Demo');
48
49 const [count,setCount] = React.useState(0)
50 const myRef = React.useRef()
51
52 React.useEffect(()=>{
53 let timer = setInterval(()=>{
54 setCount(count => count+1 )
55 },1000)
56 return ()=>{
57 clearInterval(timer)
58 }
59 },[])
60
61 //加的回调
62 function add(){
63 //setCount(count+1) //第一种写法
64 setCount(count => count+1 )
65 }
66
67 //提示输入的回调
68 function show(){
69 alert(myRef.current.value)
70 }
71
72 //卸载组件的回调
73 function unmount(){
74 ReactDOM.unmountComponentAtNode(document.getElementById('root'))
75 }
76
77 return (
78 <div>
79 <input type="text" ref={myRef}/>
80 <h2>当前求和为:{count}</h2>
81 <button onClick={add}>点我+1</button>
82 <button onClick={unmount}>卸载组件</button>
83 <button onClick={show}>点我提示数据</button>
84 </div>
85 )
86 }
87
88 export default Demo
1.作用:可以不用必须有一个真实的DOM根标签了
2.代码
1 import React, { Component,Fragment } from 'react'
2
3 export default class Demo extends Component {
4 render() {
5 return (
6 <Fragment key={1}>
7 <input type="text"/>
8 <input type="text"/>
9 </Fragment>
10 )
11 }
12 }