乐趣区

关于javascript:Day-40100-React-Hook之useContext基本用法

(一)需要

最近在学习 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
或者能够关注我的公众号:国星聊成长(我会分享成长的办法)

退出移动版