React.createContext的使用以及useContext的使用

使用createContext进行跨组件间数据传递方法
首先需要在父组件中定义一个容器和需要传递的默认值,然后通过Provider(生产者,简单来说就是定义数据的东西),定义共享的数据,然后通过Consumer(消费者,就是子组件或孙子组件来使用),具体实现代码如下:

// 在父组件中定义
export const Context = React.createContext({ activeKey: null });

// 定义需要共享的数据
<Context.Provider value={{activeKey:'lx'}}>
	<son />
</Context.Provider>

// 子组件内容中获取数据可以采用hooks写法和非hooks写法两种来获取
//非hooks写法如下,先引入定义的的Context
import Context from './parent'
<Context.Consumer>
   {(name ) => 
   		<p>获取传递下来的值:{name.activeKey}</p>
    }
</Context.Consumer>


// react16.8版本之后增加了hooks,可以使用hooks中的useContext来获取消费者

import {useContext} from 'react'
const { activeKey } = useContext(Context);// 直接这样定义就可以拿到consumer的值,然后直接当成变量使用即可,省去了之前要定义在Consumer中才能使用。
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
import React, { useState, PropsWithChildren } from "react" interface AppStateValue { username: string shoppingCart: { id: number; name: string }[] } const defaultContextValue: AppStateValue = { username: "JOKER", shoppingCart: [], } export const appContext = React.createContext(defaultContextValue) export const appSetStateContext = React.createContext< React.Dispatch<React.SetStateAction<AppStateValue>> | undefined >(undefined) export const DemoStateProvider: React.FC<PropsWithChildren<{}>> = props => { const [state, setState] = useState(defaultContextValue) return ( <appContext.Provider value={state}> <appSetStateContext.Provider value={setState}> {props.children} </appSetStateContext.Provider> </appContext.Provider> ) } import React, { useContext } from "react" import styles from "./Robot.module.css" import { appContext, appSetStateContext } from "../demoState" interface RobotProps { id: number name: string email: string } const Robot: React.FC<RobotProps> = ({ id, name, email }) => { const value = useContext(appContext) const setState = useContext(appSetStateContext) const addToCart = () => { console.log(setState, "@@") if (setState) { // 思考: 同学们可以想一想如何化简这里的代码 setState(state => { console.log(state, "??") return { ...state, shoppingCart: [...state.shoppingCart, { id, name }], } }) } } return ( <div className={styles.cardContainer}> <img alt='robot' src={`https://robohash.org/${id}`} /> <h2>{name}</h2> <p>{email}</p> <p>作者:{value.username}</p> <button onClick={addToCart}>加入购物车</button> </div> ) } export default Robot console.log(setState, "@@") 为什么这里式undefined
06-07

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值