在 React 的世界中,有容器组件和 UI 组件之分,在 React Hooks 出现之前,UI 组件我们可以使用函数组件,无状态组件来展示 UI,而对于容器组件,函数组件就显得无能为力,我们依赖于类组件来获取数据,处理数据,并向下传递参数给 UI 组件进行渲染。React在v16.8 的版本中推出了 React Hooks 新特性,Hook是一套工具函数的集合,它增强了函数组件的功能,hook不等于函数组件,所有的hook函数都是以use开头。
使用 React Hooks 相比于从前的类组件有以下几点好处:
保存组件状态,功能类似于类组件中的this.state状态管理
定义函数组件rcf
函数组件中,从react16.8之后,提供一个hook函数 useState方法,它可以模拟出状态
let [变量,函数] = useState(值|()=>值)import React from 'react';
const App = () => {
return (
<div>
</div>
);
}
export default App;
相当于在App函数组件是定义一个state数据,变量名为 count,修改此count的值的方法为setCount
const App = () => {
// let[count ,setCount] = useState(100)
let[count,setCount] = useState(()=>100)
let[count1,setCount1] = useState(()=>200)
const add = ()=>{
setCount(count+1)
}
const add1 = ()=>{
setCount1(count1+1)
}
return (
<div>
<h1>{count}</h1>
<h1>{count1}</h1>
<button onClick={add}>add</button>
<button onClick={add1}>add1</button>
</div>
);
}
export default App;

let[count,setCount] = useState(()=>100)
const add = ()=>{
setCount(count+1)
setCount(count+1)
setCount(count+1)
setCount(count+1)
}
const add = ()=>{ setCount(v=>v+1) setCount(v=>v+1) setCount(v=>v+1) setCount(v=>v+1) }'运行
const App = () => {
let [username,setUsername] = useState('')
let [password,setPassword] = useState('')
return (
<div>
姓名:<input type="text" value={username} onChange={(e)=>setUsername(e.target.value)}/><br/>
密码:<input type="text" value={password} onChange={e=>setPassword(e.target.value)}/>
</div>
);
}
必须是以use开头的函数,注意事件名必须是大写
function useForm(inintStart = ''){ let [value,setValue] = useState(inintStart) return {value,onChange:e=>setValue(e.target.value.trim())} }'运行
let username = useForm("");
let password = useForm("");
姓名:<input type="text" {...username}/><br/>
密码:<input type="text" {...password}/>
然后就可以提取出去这个函数成为hook文件封装
import {useState}from 'react';
function useForm(inintStart = ''){
let [value,setValue] = useState(inintStart)
return {value,onChange:e=>setValue(e.target.value)}
}
export default useForm
import useForm from "@/hook/useForm.js"
let username = useForm("");