useContext
可以帮助我们跨越组件层级直接传递变量,实现共享,相当于class组件时的props,用于传值
import React from "react";
const myContext = React.createContext();
function Com3() {
const { num, setNum } = React.useContext(myContext);
return (
<div>
{num} <br />
<button onClick={() => setNum(num + 2)}>num+2</button>
</div>
);
}
function Com2() {
const { count, setCount, num, setNum } = React.useContext(myContext);
return (
<div>
{count} <br />
<button onClick={() => setCount(count + 1)}>count+1</button>
<br />
{num} <br />
<button onClick={() => setNum(num + 2)}>num+2</button>
</div>
);
}
function Com1() {
return (
<div>
<Com2 />
</div>
);
}
function Example() {
const [count, setCount] = React.useState(0);
const [num, setNum] = React.useState(0);
return (
<div>
<myContext.Provider value={{ count, setCount, num, setNum }}>
<div>
<Com1 />
</div>
</myContext.Provider>
<myContext.Provider value={{ num, setNum }}>
<div>
<Com3 />
</div>
</myContext.Provider>
</div>
);
}
export default class App extends React.Component {
render() {
return (
<div>
<Example />
<hr />
</div>
);
}
}
其实主要的就是三步
1、const xxx = React.createContext();
创建一个context
2、<xxx.Provider value={{ num, setNum }}>
父组件设置要传递的值
3、const { num, setNum } = React.useContext(xxx);
子组件下使用
特点:
1、可以有多个xxx.Provider
2、可以跨组件传递
3、可以传递多个值
例子:useContext与useReducer结合使用
import React, { useReducer, useContext, createContext } from "react";
const initialState = { count: 0 };
const myContext = createContext();
function reducer(state, action) {
switch (action.type) {
case "reset":
return initialState;
case "increment":
return { count: state.count + 1 };
case "decrement":
return { count: state.count - 1 };
default:
return state;
}
}
function Counter() {
const { state, dispatch } = useContext(myContext);
return (
<div>
Counter count:{state.count}
<button onClick={() => dispatch({ type: "reset" })}>reset</button>
<button onClick={() => dispatch({ type: "increment" })}>+</button>
<button onClick={() => dispatch({ type: "decrement" })}>-</button>
</div>
);
}
function CounterTest() {
const { state, dispatch } = useContext(myContext);
return (
<div>
CounterTest count:{state.count}
<button onClick={() => dispatch({ type: "reset" })}>reset</button>
<button onClick={() => dispatch({ type: "increment" })}>+</button>
<button onClick={() => dispatch({ type: "decrement" })}>-</button>
</div>
);
}
function Contextprovider() {
const [state, dispatch] = useReducer(reducer, initialState);
return (
<myContext.Provider value={{ state, dispatch }}>
<Counter />
<CounterTest />
</myContext.Provider>
);
}
export default class App extends React.Component {
render() {
return <Contextprovider />;
}
}