react-hook之useContext

文章目录

    • 为什么要使用useContext
    • 使用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>
        {
     /*  */}
     </ThemeContext.Provider>
    </div>
  );
}

export default App;

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

   <ThemeContext.Provider value={
     themes.dark}>
 
        <LikeBUtton></LikeBUtton>
        {
     /*  */}
     </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

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

你可能感兴趣的:(fly,in,React,stumbling,in,typescript)