react-hook之useContext

为什么要使用useContext

在一个典型的react应用中,属性props是由父级逐渐传递到子级的,由于 逐级传递,所以在某些层级很多的项目中传递props属性的过程非常麻烦,我们需要定义一个全局属性,可以使他的子组件都能拿到,这是就可以用useContext

使用useContext传递样式

先到App.tsx文件中写


import React,{useState}from 'react';

import './App.css';

import LikeBUtton from './components/LikeButton';
'
interface IThemeProps{
  [key:string]:{color:string;background:string}
}

const themes: IThemeProps = {
  'light':{
    color:'#000',
    background:'#eee'
  },
  'dark':{
    color:'#fff',
    background:'#222'
  }
}
export const ThemeContext =React.createContext(themes.dark)//里面的参数是默认值

function App() {

 

 
  

  return (
   <div style={{margin:"auto 0"}}>
     <ThemeContext.Provider value={themes.dark}>
 
        <LikeBUtton></LikeBUtton>
        {/* <MouseTrack></MouseTrack> */}
     </ThemeContext.Provider>
    </div>
  );
}

export default App;

上面导出了写的ThemeContext 对象,要想让它的子组件能够拿到此属性,就必须加上

   <ThemeContext.Provider value={themes.dark}>
 
        <LikeBUtton></LikeBUtton>
        {/* <MouseTrack></MouseTrack> */}
     </ThemeContext.Provider>

包裹likebutton子组件

下面是LikeBUtton子组件拿到属性使用的代码

import React,{useState,useEffect,useRef,useContext} from 'react'
import {ThemeContext} from '../App'

const LikeBUtton:React.FC = () =>{
 
    const theme =useContext(ThemeContext)
    console.log(theme);
    const style = {
        background:theme.background,
        color:theme.color
    }


    useEffect(()=>{
        console.log("running.....");
        
        document.title = `点击了${like}次`
    },[like])
    useEffect(()=>{
        if(domRef&&domRef.current){
            domRef.current.focus()
        }

    })


 
    return (
        <>
 
            <button style={style} onClick = {()=>{setLike(like+1); likeRef.current++}}>
                {like}
            </button>
       
        </>
    )

}


export default LikeBUtton

使用之前先导入,然后可以直接调用

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值