React Hooks
React笔记
Hooks
作用: 让函数式组件用 state, props, refs的属性
三个常用Hook
State Hook: React.useState() Effect Hook: React.useEffect() Ref Hook: React.useRef()
|
State Hook
嵌套函数回调来实现增加
import React, { useState } from 'react';
function Dome() { console.log("我是Dome")
{} const [count, setCount] = useState(0);
{} function add() { setCount(count => count+1) }
return ( <div> <h1>点了{count}次</h1> <button onClick={(add) => 点我+1 </button> </div> ); }
|
嵌套函数回调来实现增加和改名
import React, { useState } from 'react';
function Dome() { console.log("我是Dome")
{} const [count, setCount] = React.useState(0); const [count, setName] = React.useState("史迪奇");
{} function add() { setCount(count => count+1) } function changeName() { setName("史迪仔") }
return ( <div> <h1>点了{count}次</h1> <button onClick={(add) => 点我+1 </button> <button onClick={(changeName) => 点我改名 </button> </div> ); }
|
Effect Hook
- Effect Hook 可以让你在函数组中执行副作用操作(用于模拟类组件中的生命钩子) 说白了就是使用生命周期钩
React中的副作用操作:
- 发ajax请求数据获取
- 设置订阅 / 启动定时器
- 手动更改真实DOM
语法和说明:
{} useEffect (() => { {} return () => { {} } {} }, [stateValue])
|
可以把useEffect Hook 看做这三个函数的组合
- componentDidMount()
- componzentDidUpdate()
- componentWillUnmount()
import React from 'react' import ReactDOM from 'react-dom'
function Demo(){
const [count,setCount] = React.useState(0) {} const myRef = React.useRef()
React.useEffect(()=>{ let timer = setInterval(()=>{ setCount(count => count+1 ) },1000) return ()=>{ clearInterval(timer) } },[])
function add(){ setCount(count => count+1 ) }
function show(){ alert(myRef.current.value) }
function unmount(){ ReactDOM.unmountComponentAtNode(document.getElementById('root')) }
return ( <div> <input type="text" ref={myRef}/> <h2>当前求和为:{count}</h2> <button onClick={add}>点我+1</button> <button onClick={unmount}>卸载组件</button> <button onClick={show}>点我提示数据</button> </div> ) }
export default Demo
|
Ref Hook
- 可以在函数组件中储存/查找组件内的标签或任意其它数据
- 语法: const refContainer = useRef()
- 作用: 保存标签对象, 功能与React.createRef()一样
import React from 'react' import ReactDOM from 'react-dom'
function Demo(){
const [count,setCount] = React.useState(0) {} const myRef = React.useRef()
React.useEffect(()=>{ let timer = setInterval(()=>{ setCount(count => count+1 ) },1000) return ()=>{ clearInterval(timer) } },[])
function add(){ setCount(count => count+1 ) }
function show(){ alert(myRef.current.value) }
function unmount(){ ReactDOM.unmountComponentAtNode(document.getElementById('root')) }
return ( <div> <input type="text" ref={myRef}/> <h2>当前求和为:{count}</h2> <button onClick={add}>点我+1</button> <button onClick={unmount}>卸载组件</button> <button onClick={show}>点我提示数据</button> </div> ) }
export default Demo
|
作者: 我叫史迪奇
本文来自于:
https://sdq3.link/React-Hooks.html博客内容遵循 署名-非商业性使用-相同方式共享 4.0 国际 (CC BY-NC-SA 4.0) 协议