- props——父子组件
//父组件中直接传递变量名,子组件中props拿到
function Father(){
const a=100;
return(
<>
<Child1 a={a} />
</>
)}
function Child1(props){
const {a}=props;
return(
<div>{a}</div>
)
}
- useContext:局部的全局上下文变量——祖先和后代组件
//声明一个context变量
const context变量名=React.createContext(null);
//父组件中provider
function Father(){
return(
<context变量名.Provider value={{a,seta}}>
<Child1 >
<GrandChildren1> </GrandChildren1>
</ Child1>
)}
//后代组件中都可以直接使用
function Child1(){
const {a,seta}=React.useContext(context变量名);
}
function GrandChildren1(){
const {a,seta}=React.useContext(context变量名);
}
3. useReducer——需要对几个数据进行更新/操作
每次数据更新的时候会重新渲染
const initial={n:0}
const reducer=(state,action){
if(action.type==="a"){
}else{ throw new Error()}
}
function APP(){
//传入一个处理函数r
const [state,dispatch]=useReducer(reducer,initial);
const onClick=()=>{
// dispatch参数是type和新的data
dispatch({type:"a",number:1})
}