高阶组件
一个函数可以接受另一个函数作为参数
例如
js
// App.js
import Children from "./children";
function App() {
return (
<div>
<Children/>
</div>
);
}
export default App;
// children.js
import Components from "./components.js";
function Children(props) {
return (
<div>我的姓名:{props.name}</div>
);
}
export default Components(Children);
// Components.js
import { Component } from "react";
function CompentUnit(Compnent) {
return class extends Component{
constructor(){
super();
this.state = {
name: '张三'
}
}
render(){
return (
<Compnent {...this.state}/>
)
}
}
}
export default CompentUnit;
hooks
React Hooks 的意思是,组件尽量写成纯函数,如果需要外部功能和副作用,就用钩子把外部代码"钩"进来
react hooks:
useState
useEffect
useRef
useReducer
useState
js
import { Component } from "react"
class App extends Component {
constructor(props) {
super(props);
this.state = {
number: 1
}
}
state = {}
render() {
return (
<div>
{this.state.number}
<button onClick={() => this.addClick()}>点击</button>
</div>
);
}
addClick() {
let num = this.state.number;
this.setState(
{
number: ++num
}
)
}
}
export default App;
useEffect
useEffect 使用方法 useEffect(()=>{ 参数方法 },[依赖参数])
useEffect未写依赖参数。为undefined
js
import { useEffect,useState } from "react"
function App() {
const [name, setName] = useState('张三')
useEffect(()=>{
console.log('修改了');
})
return (
<div>
<h1>{name}</h1>
<button onClick={()=>{
setName('王五')
}}>修改姓名</button>
</div>
);
}
export default App;
useEffect 未填写依赖参数 。[]
js
import { useEffect,useState } from "react"
function App() {
const [name, setName] = useState('张三')
useEffect(()=>{
console.log('修改了');
},[])
return (
<div>
<h1>{name}</h1>
<button onClick={()=>{
setName('王五')
}}>修改姓名</button>
</div>
);
}
export default App;
useEffect 填写依赖参数 [状态]
js
import { useEffect,useState } from "react"
function App() {
const [name, setName] = useState('张三')
useEffect(()=>{
console.log('修改了name');
},[name])
return (
<div>
<h1>{name}</h1>
<button onClick={()=>{
setName('王五')
}}>修改姓名</button>
</div>
);
}
export default App;
useContext
js
import { createContext,useContext,useState } from "react"
const context = createContext();
function Children (){
const {name, setName} = useContext(context)
return (
<div>
<h1>{name}</h1>
<button onClick={()=>{
setName('王五')
}}>修改姓名</button>
</div>
)
}
function Father() {
return (
<Children/>
)
}
function App() {
const [name, setName] = useState('李四')
return (
<context.Provider value={{name,setName}}>
<Father/>
</context.Provider>
);
}
export default App;
useReaducer
js
import { useReducer } from "react"
function App() {
const disopseFn = (state, action) => {
console.log(state,action);
switch (action.type) {
case 'change':
return { ...state, ...action.value };
default:
throw new Error()
}
}
const [props, disopse] = useReducer(disopseFn, { name: '李四', age: 12 })
return (
<div>
<h1>姓名:{props.name}</h1>
<h1>年龄: {props.age}</h1>
<button onClick={() =>
disopse({ type: 'change', value: { name: '张三' } })
}>修改姓名</button>
</div>
);
}
export default App;