likes
comments
collection
share

Day 40/100 React Hook之useContext基本用法

作者站长头像
站长
· 阅读数 16

(一)需求

最近在学习React,学到了React Hook 做了 useContext Demo。

(二)介绍

使用useContext是为了方便爷孙组件间传值。

//爷爷组件 
/*
 * @Author: ArdenZhao
 * @Date: 2022-04-16 09:48:50
 * @LastEditTime: 2022-04-16 15:14:57
 * @FilePath: /react-ts/src/components/react/9-ContextProvider.js
 * @Description: file information
 */
import React, { useState, createContext } from 'react';

export const context = createContext({});
export function ContextProvider({ children }) {
  const [age, setAge] = useState(18);
  const constVal = {
    age,
    setAge,
    addAge: () => setAge(age + 1),
  }
  return <context.Provider value={constVal}>{children}</context.Provider>
};

//孙子组件 
/*
 * @Author: ArdenZhao
 * @Date: 2022-04-16 09:30:20
 * @LastEditTime: 2022-04-16 15:05:44
 * @FilePath: /react-ts/src/components/react/9-Hook-useContext.js
 * @Description: 爷孙组件传值
 */
import { useContext } from 'react';
import { Button } from 'antd';
import "antd/dist/antd.css";
import { context, ContextProvider } from './9-ContextProvider';

function HookUseContext(props) {
  const { age, addAge } = useContext(context);
  const clickX = () => {
    addAge(age);
  }

  return (
    <div>
      <h1>Learn, {props.name}</h1>
      <p>
        实现计数器方法:{age}
      </p>
      <Button onClick={clickX}>
        useState Click +1
      </Button>
    </div>
  );
}
// eslint-disable-next-line import/no-anonymous-default-export
export default () => {
  return (
    <ContextProvider>
      <HookUseContext name="useContext" />
    </ContextProvider>
  )
}

写在最后的话

学习路上,常常会懈怠。

《有想学技术需要监督的同学嘛~》https://mp.weixin.qq.com/s/Fy...

如果有需要的伙伴,可以加我微信:learningisconnecting或者可以关注我的公众号:国星聊成长(我会分享成长的方法)